CSV with spaces around the comma

Suppose I have a CSV file with spaces around the comma:

'1','2','3', '4' '5','6','7', '8' 

If I use the Python CSV package, values 4 and 8 handled differently:

 >>> with open('/tmp/nums.csv','rU') as fin: ... for row in csv.reader(fin,quotechar="'"): ... print row ... ['1', '2', '3', " '4'"] ['5', '6', '7', " '8'"] 

Is there a way to fix this using the CSV module? I know that I can read and parse the file myself, but I am wondering if there is a dialect in the CSV package to fix this.

+4
source share
1 answer

Set skipinitialspace to True to skip spaces after the separator:

If True , the space following the delimiter is ignored. The default is False .

Demo:

 >>> import csv >>> demo='''\ ... '1','2','3', '4' ... '5','6','7', '8' ... ''' >>> for row in csv.reader(demo.splitlines(True), skipinitialspace=True, quotechar="'"): ... print row ... ['1', '2', '3', '4'] ['5', '6', '7', '8'] 
+6
source

Source: https://habr.com/ru/post/1487657/


All Articles