python - 从 csv 文件中读取并保存特定列
问题描述
需要帮忙!使用以前的主题,我发现了如何从 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
推荐阅读
- tensorflow - tf.compat.v1 和 tf.compat.v2 的别名和区别是什么?
- python - guizero Raspberry Pi:按钮 -> 命令序列问题
- flutter - Dart:如何检查非常具体的异常?
- html - VBA网页抓取更新
- r - 使用 nlm() 优化函数中的常量
- c# - 在 ASP.NET 中按角色重定向登录
- c# - Entity Framework Core 如何在生产环境中执行迁移
- oracle - 如何比较oracle中的两个集合值?
- java - Bitshifts:如何在 Java 中将十进制转换为位移值
- rust - 何时在方法中使用 self、&self、&mut self?