我有一个 csv 文件,其中包含 50 行数据,我想将其拆分为每行的单独 csv 文件,其中包括第一行(标题)和相关行。
例如。
文件 1 包含:行 1、行 2、
文件 2 包含:row1、row3、
文件 3 包含:row1、row4
等等。
目前与:
import csv
counter = 1
with open('mock_data.csv', 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
filename = "file_%s" % str(counter)
with open(filename, 'w') as csvfile_out:
writer = csv.writer(csvfile_out)
writer.writerow(row)
counter = counter + 1
我目前未定义“csvfile_out”。
a)我是否正确地处理了这个问题
b) 有什么想法为什么 csvfile_out 没有被定义吗?
我已经尝试过了,它可以很好地满足您的目的。不幸的是,我没有得到任何csvfile_out error
和你的有声明在我的 Python 2.7.12 控制台中工作正常。
import csv
counter = 1
with open('mock_data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
row1 = next(reader) # here you save your first line of the .csv file
for row in reader:
if row: # if row is not empty, write a file with this row
filename = "file_%s" % str(counter)
with open(filename, 'w') as csvfile_out:
writer = csv.writer(csvfile_out)
writer.writerow(row1) #here you write your row1 as first row of csvfile_out
writer.writerow(row)
counter = counter + 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)