我刚刚开始学习Python,我正在尝试执行以下操作: -读取.csv文件 -将过滤后的数据写入第7列不是空白/空的新文件中
当我打印结果时,它在python架子上显示正确的输出,但是当我检查.csv中的数据不正确时(与打印功能显示的内容不同) 我的代码有什么建议吗?
谢谢。
file = open("station.csv", "r")
writeFile = open("stations-filtered.csv", "w")
for line in file:
line2 = line.split(",")
if line2[7] != "":
print(line)
writeFile.write(line)
答案 0 :(得分:2)
我同意@ user513093,您可以使用csv
,例如:
file = open("station.csv", "r")
writeFile = open("stations-filtered.csv", "w")
writer = csv.writer(writeFile, delimiter=',')
for line in file:
line2 = line.split(",")
if line2[7] != "":
print(line)
writer.writerow(line)
但是pandas
仍然不错:
import pandas as pd
file = pd.read_csv("station.csv", sep=",", header=None)
file = file[file[7] != ""]
file.to_csv("stations-filtered.csv")