需要帮助!使用先前的主题,我发现了如何读取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()
答案 0 :(得分:0)
我尝试了以下代码,但工作正常
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