我目前有一個200k行的csv文件,每行包括80個條目,用逗號分隔。我嘗試用open()打開csv文件並將數據追加到2-D python列表中。當我嘗試遍歷該列表並將80個條目添加到單個列表中時,計算機會凍結。我的代碼是否會產生某種內存問題?我應該分批處理數據嗎?還是有更有效的方法來解決我想要做的事情?如何在python中遍歷大型CSV文件時輕鬆實現內存?
簡而言之:打開csv,經過200k條目並將它們從[1,2,3,4,5,...,80],[1,...,80],.. .. 200k - > [12345 ... 80]。 [1 ... 80],200K
import csv
# create empty shells
raw_data = []
concatenate_data = []
def get_data():
counter = 1
# open the raw data file and put it into a list
with open('raw_data_train.csv', 'r') as file:
reader = csv.reader(file, dialect='excel')
for row in reader:
print('\rCurrent item: {0}'.format(counter), end='', flush=True)
raw_data.append(row)
counter += 1
print('\nReading done')
def format_data():
counter = 1
temp = ''
# concatenate the separated letters for each string in the csv file
for batch in raw_data:
for letters in batch:
temp += letters
concatenate_data.append(temp)
print('\rCurrent item: {0}'.format(counter), end='', flush=True)
counter += 1
print('\nTransforming done')
print(concatenate_data[0:10])
是正常的'temp'只在啓動時進行更快的使用
str.join
避免字符串連接呢? –@ Jean-FrançoisFabre你是什麼意思?我只需要暫時使用這個變量來保存80個單個條目並將它們轉換爲單個條目。這就是爲什麼它只包含在格式數據函數中。 – d3x