简体   繁体   中英

python readline by '\r\n'

How can I called f.readline() where the line delimeter is \\r\\n ?

This CSV file is very large so I can't do f.read().split('\\r\\n') .

Instead I'm hoping for f.readline('\\r\\n') .

Here is a typical line:

1, "ABC", "the quick \n brown fox \n jumps over the \n lazy dogs", 5 \r\n

It seems you're actually trying to read a CSV file (or something like it) where newlines that are embedded in quotes need to be ignored.

That's something the csv module already handles for you.

import csv
with open("myfile", "rb") as infile:
    reader = csv.reader(infile, delimiter=",", skipinitialspaces=True)
    for line in reader:
       print line

If you don't use csv , then open the file with universal newlines support :

f = open('big_csv_file.csv', 'rU')

This will cause f.readline() to interpret \\n , \\r\\n and \\r equally, each as a newline.

From the csv python documentation

>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') #<--- Note the
                                                                       #delimiter param.
...     for row in spamreader:
...         print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

Just make a csvreader with delimiter set to '\\r\\n'. That should give you each line delimited by \\r\\n.

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