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

时间:2017-11-14 19:02:55

标签: python csv

我有一个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'

2 个答案:

答案 0 :(得分:1)

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

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

要修复它,请按以下步骤更改它们:

with open(IRIS_data, 'w', newline='') as data:

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"

答案 1 :(得分:0)

您必须对您正在编写的行进行编码,如下所示:

wr.writerow( line.encode(”utf8”))

也可以使用open(..., ‘wb’)打开您的文件。这将以二进制模式打开文件。所以你确定文件实际上是以二进制模式打开的。实际上,现在明确编码比假设更好。强制执行读写编码将为您节省大量麻烦。