【问题标题】:How to obtain rows and columns of a csv file imported in python?如何获取用python导入的csv文件的行和列?
【发布时间】:2021-06-28 05:30:23
【问题描述】:
我的应用程序有多个 csv 文件。我试图通过读取 csv 文件来获取行数和列数。我有两个通过参数 file_path 发送的 csv 文件。 第一个文件有 5 行 3 列,第二个文件有 5 行 5 列。但是使用下面的代码,我得到第一个文件有 4 行和 3 列,第二个文件有 4 行和 5 列。我不明白为什么它会跳过从行数中读取一行。
另一方面,如果我先执行 row_count 和 col_count 的代码,它会给出 StopIteration 异常。
这可能是一个非常简单的问题,但对于我是 Python 新手来说,非常感谢任何帮助。谢谢
def read_text_file(file_path):
with open(file_path, 'r') as f:
reader = csv.reader(f)
col_count = len(next(reader))
print(col_count)
row_count = len(list(csv.reader(f)))
print(row_count)
【问题讨论】:
标签:
python
csv
file
file-handling
stopiteration
【解决方案1】:
读取 CSV 并将其存储在列表中
reader = list(csv.reader(f))
这会将csv数据变成二维数组,然后你就可以使用len()函数了。
【解决方案2】:
import numpy
numpy.genfromtxt('path/to/your/csv/file.csv').shape
应该以元组的形式告诉你行数和列数。
【解决方案3】:
问题是文件有一个位置的概念。当您打开它时,该文件位于开头。让我们看看你的来源:
def read_text_file(file_path):
with open(file_path, 'r') as f: // file is opened, pointing at first char
reader = csv.reader(f) // reader will use file
col_count = len(next(reader)) // next(reader) READS FIRST ROW...
print(col_count) // file is now after the first row!
row_count = len(list(csv.reader(f))) // read remaining rows
print(row_count) // number of rows minus 1...
您应该使用row_count = 1 + len(list(csv.reader(f))) 添加已读取的第一行。