List Python3:拆分列表并另存为文件-如何?
我是Python新手,谢谢你的帮助 我想告诉Python获取一个大的.csv列表,并将其拆分为许多只有两列的小列表List Python3:拆分列表并另存为文件-如何?,list,python-3.x,split,List,Python 3.x,Split,我是Python新手,谢谢你的帮助 我想告诉Python获取一个大的.csv列表,并将其拆分为许多只有两列的小列表 以这个.csv文件为例 始终使用第一列“年” 然后始终取下一列(循环?),从第2列“Object1”开始,然后是第3列“Object2”,依此类推 将每个列表另存为.csv(现在仅包含两列),并在第二列后命名(f.e.“Object1”) 到目前为止,我能做到这一点: import csv object = 0 f = open("/home/Data/data.csv") c
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()
您的代码试图打开同一文件进行读写,这可能会产生意外的结果 把你的问题看作一系列步骤;解决这个问题的一种方法是:
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