Python CSV reader TypeError: string pattern on bytes object -
i trying use python csv reader first time. have method asks user select file want parse , passes file path parse method:
def parse(filename): parsedfile = [] open(filename, 'rb') csvfile: dialect = csv.sniffer().sniff(csvfile.read(), delimiters=';,|') csvfile.seek(0) reader = csv.reader(csvfile, dialect) line in reader: parsedfile.append(line) return(parsedfile) def selectfile(): print('start selectfile method') localpath = os.getcwd() + '\files' print(localpath) filea in os.listdir(localpath): print (filea) test = false while test == false: fileb = input('which file deid? \n') conjoinedpath = os.path.join(localpath, fileb) test = os.path.isfile(conjoinedpath) userinput = input('please enter number corresponding client ' + fileb + ' belongs to. \n\nacceptable options are: \n1.a \n2.b \n3.c \n4.d \n5.e \n') client = '' if (userinput == '1'): client = 'a' elif (userinput == '2'): client = 'b' elif (userinput == '3'): client = 'cservices' elif (userinput == '4'): client = 'd' elif (userinput == '5'): client = 'e' return(client, conjoinedpath) def main(): x, y = selectfile() parse(y) if __name__ == '__main__': main() all of seems working intended, getting a:
typeerror: can't use string pattern on bytes-like object when trying open filename (line 3 in code). have tried convert filename to both string-type , byte-type , neither seem work.
here output:
>>> start selectfile method c:\pythonscripts\deid\files 89308570_201601040630verifyppn.txt 89339985_201601042316verifyppn.txt file deid? 89339985_201601042316verifyppn.txt please enter number corresponding client 89339985_201601042316verifyppn.txt belongs to. acceptable options are: 1.client 2.client b 3.client c 4.client d 5.client e 3 traceback (most recent call last): file "c:\pythonscripts\deid\deidva1.py", line 107, in <module> main() file "c:\pythonscripts\deid\deidva1.py", line 103, in main parse(y) file "c:\pythonscripts\deid\deidva1.py", line 63, in parse dialect = csv.sniffer().sniff(csvfile.read(), delimiters=';,|') file "c:\python34\lib\csv.py", line 183, in sniff self._guess_quote_and_delimiter(sample, delimiters) file "c:\python34\lib\csv.py", line 224, in _guess_quote_and_delimiter matches = regexp.findall(data) typeerror: can't use string pattern on bytes-like object >>> i not sure doing wrong.
it not filename blamed here, fact opening file with:
with open(filename, 'rb') csvfile: where 'rb' mode specifies file opened in binary mode, is, contents of file treated byte objects. documentation:
'b'appended mode opens file in binary mode: data read , written in form of bytes objects. mode should used files don’t contain text.
then attempt search within csv.sniff().sniff() string pattern, and, typeerror gracefully points out, isn't allowed.
removing b mode , using r trick.
note: python 2.x doesn't exhibit behavior on unix machines. result of segregation of bytes , str objects distinct types in 3.x.
Comments
Post a Comment