gpt4 book ai didi

python - Python 读取和写入 csv 文件

转载 作者:行者123 更新时间:2023-12-01 00:52:13 24 4
gpt4 key购买 nike

我刚刚开始学习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)

最佳答案

我同意@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")

关于python - Python 读取和写入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com