2016-07-25 8 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」にする必要があるということでした私はそれを試して、このエラーが出た:

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' 

私はエラーが反対を行うと言っているようですe事。

答えて

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