简体   繁体   中英

How to read multiline command line arguments into a python2 CSV reader

I'm testing a Python 2 script that takes a CSV file's text as a command line argument. The CSV is a standard Excel CSV file with ',' delimiters for items and presumably '\\r\\n' for line endings.

The problem is that I need to pass the CSV text as a single line to the script in order for it to recognise the string as a single argument. In order to do this, I open the CSV in notepad and replace all of the new lines with '\\r\\n' which enables me to read the test into my script successfully. However, when I try to create a csv.reader object from the string, the csv.reader only sees a single line where I want iot to see multiple lines.

Given the following CSV string example:

The,quick,brown,fox\r\njumps,over,the,lazy,dog

I would expect the following lines:

The,quick,brown,fox
jumps,over,the,lazy,dog

but instead I just end up with a single line:

The,quick,brown,fox\r\njumps,over,the,lazy,dog

Once I capture the string from the command line, I use the following to load it into a csv.reader :

input_str = self.GetCsvStringFromInput()
input_reader = csv.reader(StringIO.StringIO(input_str))

I'm using windows so I presumed that \\r\\n would be correct but I don't seem to be using the correct method.

Any ideas? Thanks, in adv.!

Why don't you just read the lines directly from csv file? Such as:

    with open('D:/file-1.csv','r') as csvfile:
         creader=csv.reader(csvfile, delimiter=',')
         for line in creader:
             print line

just replace 'print line' with what your own function. If you do need manually copy each line from the csv file,you can try to split each line by '\\r\\n' before pass to the reader.

for line in 'The,quick,brown,fox\r\njumps,over,the,lazy,dog'.split('\r\n'):
    print line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM