1
所以我試圖通過寫入臨時文件來編輯csv文件,並最終用臨時文件替換原始文件。我將不得不多次編輯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?)
所以我搜索了這個錯誤和一般的共識是,「RB」需要「RT」,所以我想,和得到這個錯誤:因爲錯誤似乎在說做opposit
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'
我很困惑東西。
完美!謝謝! – catoejr