Parse one line of CSV?

Is there a way that I can parse a single comma-delimited line without using anything similar to csv.reader (..)? I can use the split(',') function, but this does not work when a valid column value contains a comma. There are readers in the csv library for parsing CSV files that correctly handle the above special case, but I cannot use them because I only need to parse one line. However, if Python CSV allows you to parse a single line, then this news is for me.

+5
source share
2 answers

Check out the documentation for the csv module, which says:

 reader(...) csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) The "iterable" argument can be any object that returns a line of input for each iteration, such as a file object or a list. The optional "dialect" parameter is discussed below. The function also accepts optional keyword arguments which override settings provided by the dialect. 

So, if you have a line:

 >>> s = '"this is", "a test", "of the csv", "parser"' 

And you want an “object that returns an input string for each iteration”, you can simply wrap your string in a list:

 >>> r = csv.reader([s]) >>> list(r) [['this is', 'a test', 'of the csv parser']] 

And how do you parse the string with the csv module.

+11
source

You can still parse one line using csv . Use StringIO to write the string buffer (also known as memory files):

 import csv from StringIO import StringIO s = "your string" buff = StringIO(s) reader = csv.reader(buff) for line in reader: print(line) 
+10
source

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


All Articles