【问题标题】:Does csv.DictReader store file in memory?csv.DictReader 是否将文件存储在内存中?
【发布时间】:2016-12-24 22:14:58
【问题描述】:

我必须读取文件中几乎有 100K 行的大型 CSV 文件,如果我能以字典格式读取每个文件行,处理该文件将非常容易。

经过一番研究,我从 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

【问题讨论】:

    标签: python-2.7 csv dictionary in-memory


    【解决方案1】:

    据我所知,您创建的 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)
    

    希望这会有所帮助! 卢克

    【讨论】:

      猜你喜欢
      • 2012-08-30
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2015-11-16
      相关资源
      最近更新 更多