unnecessary "['', '']" when parse CSV files using python csv module -
everyone.
i want parse csv "20568078","240431","jpg","st, carolina 1920",,
into ["20568078","240431","jpg","st, carolina 1920","",""]
by using this:
string=r'"20568078","240431","jpg","st, carolina 1920",,' reader = csv.reader(string) r in reader: print (r)
i got output:
['20568078'] ['', ''] ['240431'] ['', ''] ['jpg'] ['', ''] ['st, carolina 1920'] ['', ''] ['', '']
i want konw how delete unnecessary ['', '']
, , change last 2 ,,
""
, ""
thank you.
use stringio
treat stings file-like object
>>> import csv >>> stringio import stringio >>> string=r'"20568078","240431","jpg","st, carolina 1920",,' >>> r in csv.reader(stringio(string)): print (r) ['20568078', '240431', 'jpg', 'st, carolina 1920', '', '']
http://docs.python.org/2/library/csv.html#csv.reader
csv.reader(csvfile, dialect='excel', **fmtparams)
return reader object iterate on lines in given
csvfile
.csvfile
can object supports iterator protocol , returns string each timenext()
method called —file
objects ,list
objects both suitable.
the problem code passing single string reader
. reader interprets each character line. eg.
>>> string=r'"20568078","240431","jpg","st, carolina 1920",,' >>> = iter(string) >>> next(i) '"' >>> next(i) '2'
is approximately how csv
calls next
on iterable pass it. use doublequotes represent multiline strings explains why come in 1 piece.
Comments
Post a Comment