![](/img/trans.png)
[英]Copy specific Column from a .csv file to another .csv file and save it as a new .csv file issue
[英]read and save a specific column from csv file
需要帮忙! 通过使用先前的主题,我发现了如何读取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()
样本文件:
FILE.CSV
a,b,c,d,e
f,g,h,i,j
k,l,m,,n
,,,o,
new.csv
d
i
o
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.