readling newlines

Discussion in 'Python' started by Alessandro Crugnola *sephiroth*, Jan 10, 2004.

  1. Hi, I'm trying to detect the newlines method of a file opened.
    I'm using the 'U' mode as parameter when opening a file, but for every file opened the result is always "\r\n", even if the file has
    been saved with the "\n" newline method.
    Is there i'm missing?

    I'm on Windows with python 2.3.3
    Alessandro Crugnola *sephiroth*, Jan 10, 2004
    1. Advertisements

  2. |Thus Spake Alessandro Crugnola *sephiroth* On the now historical date of
    Sat, 10 Jan 2004 14:25:44 +0000|
    Not quite sure what "U" mode is, but try adding the "b" mode when opening
    the file. Windows makes a distinction between binary and text files.
    Python defaults to text mode, and since newlines for windows text is \r\n,
    that's what Python puts there.


    Sam Walters.
    Samuel Walters, Jan 11, 2004
    1. Advertisements

  3. Alessandro Crugnola *sephiroth*

    Peter Otten Guest

    Here's what I get (on Linux):
    .... dst = file("tmp.txt", "wb")
    .... dst.write("one%stwo" % nl)
    .... dst.close()
    .... print repr(file("tmp.txt", "U").read())
    From the documentation of file():

    If Python is built without universal newline support mode 'U' is the same as
    normal text mode.

    So maybe you have a version without universal newline support?

    Peter Otten, Jan 11, 2004
  4. Samuel Walters wrote in message ...
    FYI, 'U' is universal newline mode, which will quietly convert the newline
    convention of a file into '\n'. I think it has some rudamentary ability to
    handle mixed-convention newline ugliness.

    See the documentation on file() in the library reference, and there's a PEP
    on the feature, too.
    Francis Avila, Jan 11, 2004
  5. Alessandro Crugnola *sephiroth*

    John Roth Guest

    file opened the result is always "\r\n", even if the file has
    Regardless of what you tell it, Python will always write a text
    file with the operating system's line separators. In Windows,
    that's \r\n. Universal newline mode only operates on input,
    and will translate *all* common system's line separators into

    In other words, if you write a file in text mode using /n, and
    then read it back in binary mode, you'll see /r/n for the line
    separators. Universal newline support does not change this
    because it does not change what you see in binary mode.

    John Roth
    John Roth, Jan 11, 2004
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.