Text file with mixed end-of-line terminations

Discussion in 'Python' started by Alex van der Spek, Aug 31, 2011.

  1. 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
    Alex van der Spek, Aug 31, 2011
    #1
    1. Advertising

  2. Alex van der Spek

    Chris Rebert Guest

    On Wed, Aug 31, 2011 at 12:37 PM, Alex van der Spek <> wrote:
    > 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'

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


    Universal Newline Support
    http://www.python.org/dev/peps/pep-0278/

    http://docs.python.org/library/functions.html#open
    (Modes involving "U")

    Cheers,
    Chris
    Chris Rebert, Aug 31, 2011
    #2
    1. Advertising

  3. Alex van der Spek

    woooee Guest

    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
    woooee, Sep 1, 2011
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. kaushikshome
    Replies:
    4
    Views:
    753
    kaushikshome
    Sep 10, 2006
  2. walterbyrd
    Replies:
    7
    Views:
    300
    Asun Friere
    May 17, 2007
  3. scad
    Replies:
    23
    Views:
    1,144
    Alf P. Steinbach
    May 17, 2009
  4. Jimmy
    Replies:
    3
    Views:
    315
    J. J. Farrell
    Sep 9, 2011
  5. Jimmy
    Replies:
    13
    Views:
    639
    Peter Nilsson
    Sep 21, 2011
Loading...

Share This Page