所以我试图通过写入临时文件来编辑csv文件,并最终用temp文件替换原始文件。我将不得不多次编辑csv文件,因此我需要能够引用它。我之前从未使用过NamedTemporaryFile命令,而且我遇到了很多困难。我遇到的最持久的问题是在编辑的行上书写。
除非特定值在特定列中,然后它才会传递,否则此部分将遍历并写入行。
我有这个:
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, "rb") as oi, temp:
r = csv.reader(oi)
w = csv.writer(temp)
for row in r:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
w.writerow(row)
我收到此错误:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 63, in cleanOfficeCol
for row in r:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
所以我搜索了这个错误,而普遍的共识就是&#34; rb&#34;需要成为&#34; rt&#34;所以我试过了,得到了这个错误:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 67, in cleanOfficeCol
w.writerow(row)
File "C:\Users\jcatoe\AppData\Local\Programs\Python\Python35-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
我很困惑,因为错误似乎是在说相反的事情。
答案 0 :(得分:1)
如果您阅读tempfile docs,则默认情况下会在'w+b'
模式下打开文件。如果你仔细看看你的错误,你会发现你正在阅读一个,一个在写。您需要做的是确保您以相同的模式打开输入和输出文件。
你可以这样做:
import csv
import tempfile
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, 'r') as oi, tempfile.NamedTemporaryFile(delete=False, mode='w') as temp:
reader = csv.reader(oi)
writer = csv.writer(temp)
for row in reader:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
writer.writerow(row)