我是Python的新手,所以感谢你的帮助!
我想告诉Python使用一个大的.csv列表并将其拆分为许多只有两列的小列表
到目前为止,我对此表示赞同:
import csv
object = 0
f = open("/home/Data/data.csv")
csv_f = csv.reader(f, delimiter=';', quotechar='|')
writer = csv.writer(csv_f)
for row in csv_f:
writer("[0],[object]")
object += 1
f.close()
答案 0 :(得分:1)
您的代码正在尝试打开相同的文件进行读写,这可能会产生意外结果。
将您的问题视为一系列步骤;解决问题的一种方法是:
以上是与上述相同的方法,充分利用了Python的csv阅读功能:
import csv
with open('big-file.csv') as f:
reader = csv.reader(f, delimiter=';', quotechar='|')
titles = next(reader)
for index, column_name in enumerate(titles[1:]):
with open('{}.csv'.format(column_name), 'w') as i:
writer = csv.writer(i, delimiter=';', quotechar='|')
for row in reader:
writer.writerow((row[0],row[index+1]))
f.seek(0) # start from the top of the big file again
next(reader) # skip the header column