Lax*_*ant 3 csv dictionary in-memory python-2.7
我必须读取一个大型 CSV 文件,文件中几乎有 100K 行,如果我能以字典格式读取每个文件行,处理该文件也会变得非常容易。
经过一番研究,我从 csv 模块中找到了 python 的内置函数csv.DictReader 。
但在文档中并没有明确提到它是否将整个文件存储在内存中。
但它提到:
fieldnames 参数是一个序列,其元素按顺序与输入数据的字段相关联。
但我不确定序列是否存储在内存中。
那么问题来了,它是否将整个文件存储在内存中?
如果是这样,是否有其他选项可以从文件中读取单行作为生成器表达式并将 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
Run Code Online (Sandbox Code Playgroud)
据我所知,您创建的 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
Run Code Online (Sandbox Code Playgroud)
使用上面的函数(或类似的函数),您可以通过几行代码来实现您的目标。例如:
data, data_fields = csv_to_dict_list(path)
print data_fields (prints fieldnames)
print data[0] (prints first row of data from file)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!卢克
| 归档时间: |
|
| 查看次数: |
3389 次 |
| 最近记录: |