我有一个简单的场景,我将CSV中的分隔符从;
(分号)更改为,
(逗号)。以下是代码
代码:
import csv
semicolonin = csv.reader(r"C:\pyscripts\1.csv", delimiter=';')
commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',')
for row in semicolonin:
commaout.writerow(row)
但我收到错误。我错过了什么吗?
TypeError: argument 1 must have a "write" method
执行第commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',')
行时。
答案 0 :(得分:2)
您必须为writer方法提供一个文件对象,如下所示:
import csv
with open(r"C:\pyscripts\1.csv") as in_file, open(r"C:\pyscripts\1.csv", 'w') as out_file:
semicolonin = csv.reader(in_file, delimiter=';')
commaout = csv.writer(out_file, delimiter=',')
for row in semicolonin:
commaout.writerow(row)
答案 1 :(得分:0)
您还可以使用熊猫:
import pandas as pd
f = pd.read_csv("C:\pyscripts\1.csv")
f.to_csv("C:\pyscripts\1.csv", sep=";")