csv.DictReader 是否将文件存储在内存中?

Does csv.DictReader store file in memory?

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

经过一些研究,我从 csv 模块中找到了 python 的内置函数 csv.DictReader

但是在文档中并没有明确提到是否将整个文件存储在内存中。

但是它提到了:

The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order.

但我不确定序列是否存储在内存中。

所以问题是,它是否将整个文件存储在内存中?

如果是这样,是否有任何其他选项可以从文件中读取单行作为生成器或表达式并将获取行读取为字典。

这是我的代码:

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)

希望对您有所帮助! 卢克