需要帮忙!使用以前的主题,我找到了如何从 csv 文件中读取数据,我对此没有问题,但我无法将特定列(例如 file.csv 中的第 4 列)保存为 new.csv 文件。我的脚本正确打印了第 4 列,但没有保存它。
import csv
with open('file.csv') as csvfile:
file1 = csv.reader(csvfile, delimiter=',')
fourth_col = []
for cols in file1:
fourth_col = cols[3]
print (fourth_col)
new_file = open('new.csv', 'w')
writer = csv.writer(new_file)
writer.writerows(fourth_col)
new_file.close()
我尝试了以下代码,它工作正常
import csv
new_file = open('new.csv', 'w')
writer = csv.writer(new_file)
with open('file.csv') as csvfile:
file1 = csv.reader(csvfile, delimiter=',')
fourth_col = []
for cols in file1:
fourth_col = cols[3]
print(fourth_col)
writer.writerows(fourth_col)
new_file.flush()
new_file.close()
示例文件:
文件.csv
a,b,c,d,e
f,g,h,i,j
k,l,m,,n
,,,o,
新的.csv
d
i
o
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句