2016-07-25 69 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