Text file with mixed end-of-line terminations

A

Alex van der Spek

I have a text file that uses both '\r' and '\r\n' end-of-line terminations.

The '\r' terminates the first 25 lines or so, the remainder is termiated
with '\r\n'

Reading this file like this:

++++++++
for line in open(filename,'r'):
line= #Do whatever needs doing...
++++++++

The first line read is actually a string consiting of the first 25 lines.
The readline() method does the same thing.

Is there a way to make it read one line at a time, regardless of the line
termination?

By the way, the newlines attribute reports None after reading a few lines. I
tried on Linux and Windows. I use the standard binaries as distributed.

Thanks in advance,
Alex van der Spek
 
W

woooee

You can use f.read() to read the entire file's contents into a string,
providing the file isn't huge. Then, split on "\r" and replace "\n"
when found.
A simple test:
input_data = "abc\rdef\rghi\r\njkl\r\nmno\r\n"
first_split = input_data.split("\r")
for rec in first_split:
rec = rec.replace("\n", "")
print rec
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top