2016-08-18 22 views
2

我必須在文件中讀取幾乎100K行的大型CSV文件,如果我能夠以字典格式讀取每個文件行,處理該文件也會非常容易。csv.DictReader是否將文件存儲在內存中?

經過一番研究,我發現csv模塊的python內置函數csv.DictReader

但在文檔中並不清楚是否將整個文件存儲在內存中。

但它提到:

的字段名的參數是一個序列,其元素與輸入數據的順序中的字段相關聯。

但我不確定序列是否存儲在內存中。

所以問題是,它是否將整個文件存儲在內存中?

如果是這樣,是否有任何其他選項從文件讀取單行作爲一個generaror表達式,並讀取get行作爲詞典。

這裏是我的代碼:

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 

回答

3

至於即時通訊意識到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 

用上面的功能(或類似的東西),你可以用幾行acheive你的目標。例如:

data, data_fields = csv_to_dict_list(path) 
print data_fields (prints fieldnames) 
print data[0] (prints first row of data from file) 

希望這有助於! Luke

相關問題