我必须读取文件中几乎有 100K 行的大型 CSV 文件,如果我能以字典格式读取每个文件行,处理该文件也会非常容易。
经过一些研究,我发现了 python 的内置函数 csv.DictReader来自 csv 模块。
但是在文档中并没有明确提到是否将整个文件存储在内存中。
但是它提到了:
The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order.
但我不确定序列是否存储在内存中。
所以问题是,它是否将整个文件存储在内存中?
如果是这样,是否有任何其他选项可以从文件中读取单行作为 generaror 表达式并将 get row 读取为 dict 。
这是我的代码:
def file_to_dictionary(self, file_path):
"""Read CSV rows as a dictionary """
file_data_obj ={}
try:
self.log("Reading file: [{}]".format(file_path))
if os.path.exists(file_path):
file_data_obj = csv.DictReader(open(file_path, 'rU'))
else:
self.log("File does not exist: {}".format(file_path))
except Exception as e:
self.log("Failed to read file.", e, True)
return file_data_obj
最佳答案
据我所知,您创建的 DictReader 对象在您的例子中是 file_data_obj
,是一个生成器类型对象。
生成器对象不存储在内存中,但只能迭代一次!
要将数据的字段名打印为列表,您可以简单地使用:print file_data_obj.fieldnames
其次,根据我的经验,我发现从 csv 文件读取数据时使用字典列表要容易得多,其中每个字典代表文件中的一行。请考虑以下事项:
def csv_to_dict_list(path):
csv_in = open(path, 'rb')
reader = csv.DictReader(csv_in, restkey=None, restval=None, dialect='excel')
fields = reader.fieldnames
list_out = [row for row in reader]
return list_out, fields
使用上面的函数(或类似的东西),你可以用几行代码来实现你的目标。例如:
data, data_fields = csv_to_dict_list(path)
print data_fields (prints fieldnames)
print data[0] (prints first row of data from file)
希望对您有所帮助! 卢克
关于python-2.7 - csv.DictReader 是否将文件存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39010449/