gpt4 book ai didi

python - 如何将一个 CSV 文件的内容写入另一个文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:02 25 4
gpt4 key购买 nike

我有一个 csv 文件,我想将不带标题的原始数据传输到新的 csv 文件,并且行和列与原始数据相同。

IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
wr = csv.writer(data, quoting=csv.QUOTE_ALL)
with open(IRIS) as f:
next(f)
for line in f:
wr.writerow(line)

上面的代码是我最近的尝试,当我尝试运行它时,出现以下错误:

a bytes-like object is required, not 'str'

最佳答案

这是因为您使用 with open(IRIS_data, 'wb') 打开了输入文件,它以二进制模式打开它,而输出文件仅使用 with open(IRIS) 以文本模式打开它。

在 Python 3 中,您应该以文本模式打开这两个文件并指定 newline='' 选项)—请参阅 csv 模块的 documentation 中的示例)

要修复它,请按如下方式更改它们:

以 open(IRIS_data, 'w', newline='') 作为数据:

with open(IRIS, newline='') as f:

但是您的代码还存在其他问题。以下是如何使用这些语句来获得我认为您想要的内容:

import csv

IRIS = "IRIS.csv"
IRIS_data = "IRIS_data.csv"

with open(IRIS, 'r', newline='') as f, open(IRIS_data, 'w', newline='') as data:
next(f) # Skip over header in input file.
writer = csv.writer(data, quoting=csv.QUOTE_ALL)
writer.writerows(line.split() for line in f)

使用示例输入数据运行脚本后 IRIS_data.csv 文件的内容:

"6.4","2.8","5.6","2.2","2"
"5","2.3","3.3","1","1"
"4.9","2.5","4.5","1.7","2"
"4.9","3.1","1.5","0.1","0"
"5.7","3.8","1.7","0.3","0"
"4.4","3.2","1.3","0.2","0"
"5.4","3.4","1.5","0.4","0"
"6.9","3.1","5.1","2.3","2"
"6.7","3.1","4.4","1.4","1"
"5.1","3.7","1.5","0.4","0"

关于python - 如何将一个 CSV 文件的内容写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293410/

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