如何从csv文件制作副本进行编辑

时间:2017-06-30 19:16:25

标签: python python-3.x

当我试图从csv文件制作副本以编辑原始文件时 然后我将效果应用到原来的

import csv
import shutil
from tempfile import NamedTemporaryFile

filename = "data1.csv"
temp_file = NamedTemporaryFile(delete=False)
print(temp_file.name)
with open(filename, "r",encoding='utf8') as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    fieldnames = ["id", "name", "email", "sent"]
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    # writer.writeheader()
    for row in reader:
        writer.writerow({
            "id":row["id"],
            "name":row["name"],
            "email":row["email"],
            "sent":""
        })

我收到此错误:/

C:\Users\Arafat\AppData\Local\Temp\tmpwgkcslas
Traceback (most recent call last):
  File "C:\Users\Arafat\Desktop\30dpython\hungry_data.py", line 49, in <module>
    "sent":""
  File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\tempfile.py", line 483, in func_wrapper
    return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:0)

错误是你的temp_file以二进制模式而不是文本模式打开的结果(默认为w+b)。将其更改为:

temp_file = NamedTemporaryFile(mode='w', encoding='utf8', delete=False)

(编码不是严格必要的,但是因为你在输入上指定它,所以在输出上指定它是有意义的。)

请参阅https://docs.python.org/3/library/tempfile.html