python 3.x - Contradicting Errors? -
so i'm trying edit csv file writing temporary file , replacing original temp file. i'm going have edit csv file multiple times need able reference it. i've never used namedtemporaryfile command before , i'm running lot of difficulties. persistent problem i'm having writing on edited lines.
this part goes through , writes on rows unless specific values in specific column , passes over.
i have this:
office = 3 temp = tempfile.namedtemporaryfile(delete=false) open(infile, "rb") oi, temp: r = csv.reader(oi) w = csv.writer(temp) row in r: if row[office] == "r00" or row[office] == "alc" or row[office] == "rms": pass else: w.writerow(row)
and error:
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 row in r: _csv.error: iterator should return strings, not bytes (did open file in text mode?)
so searched error , general consensus "rb" needs "rt" tried , got error:
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: bytes-like object required, not 'str'
i'm confused because errors seem saying opposite thing.
if read tempfile docs you'll see default it's opening file in 'w+b'
mode. if take closer @ errors, you'll see you're getting 1 on read, , 1 on write. need doing making sure you're opening input , output file in same mode.
you can this:
import csv import tempfile office = 3 temp = tempfile.namedtemporaryfile(delete=false) open(infile, 'r') oi, tempfile.namedtemporaryfile(delete=false, mode='w') temp: reader = csv.reader(oi) writer = csv.writer(temp) row in reader: if row[office] == "r00" or row[office] == "alc" or row[office] == "rms": pass else: writer.writerow(row)
Comments
Post a Comment