2016-07-25 100 views
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' 

我很困惑東西。

回答

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) 
+0

完美!謝謝! – catoejr