我对python(以及一般的编程)非常陌生。下面粘贴的代码用于编辑现有的csv。但是我收到了一个错误。 错误是
Traceback (most recent call last):
File "C:\Users\Samsung Pc\Desktop\hungrypy1\hungry_data.py", line 34, in <module>
writer.writeheader()
File "C:\Users\Samsung Pc\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 144, in writeheader
self.writerow(header)
File "C:\Users\Samsung Pc\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\Samsung Pc\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'
[Finished in 0.5s]
我试图寻找答案,它似乎是从二进制到字符串的类型不匹配。我试图将文件打开为&#34; r&#34;而不是&#34; rb&#34;然而是同样的错误。请帮忙。代码如下。
import csv
import shutil
from tempfile import NamedTemporaryFile
def get_length(file_path):
with open("data.csv", "r") as csvfile:
reader = csv.reader(csvfile)
reader_list = list(reader)
print(reader_list)
return len(reader_list)
def append_data(file_path, name, email):
fieldnames = ['id', 'name', 'email'
next_id = get_length(file_path)
with open(file_path, "a", newline = '') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({
"id": next_id,
"name": name,
"email": email,
})
append_data("data.csv", "Niraj", "test@test.com")
filename = "data.csv"
temp_file = NamedTemporaryFile(delete = False)
with open(filename, "r") as csvfile, temp_file:
reader = csv.DictReader(csvfile)
fieldnames = ['id','name','email','amount','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"],
"amount": "1234.34",
"sent": "",
})
#shutil.move(temp_file.name. filename)
答案 0 :(得分:0)
您不应同时读取和写入同一文件:
with open(filename, "r") as csvfile, temp_file:
即使您为此文件指定了两个名称,它们也指向您磁盘中的同一文件,将其更改为:
with open(filename, "r") as csvfile, open('temp_file.csv', 'w') as temp_file:
答案 1 :(得分:0)
你正在做什么:
temp_file = NamedTemporaryFile(delete = False)
with open(filename, "r") as csvfile, temp_file:
, temp_file
部分严格禁止。你必须打开文件写...
之后您使用temp_file
作为输出文件句柄,但它实际上是字符串,因此您将获得该消息。
你想这样做:
with open(filename, "r") as csvfile, open(temp_file,"w",newline='') as outfile:
然后使用outfile
,而不是temp_file
:
writer = csv.DictWriter(outfile, fieldnames = fieldnames)
除此之外:不要使用writer.writeheader()
:无论如何都会写出标题,你会得到它两次。