Re: Reading a DOS text file and writing out Mac

Discussion in 'Python' started by Skip Montanaro, Jul 11, 2003.

  1. Jen> Is there a way to set the EOL character that Python recognizes?

    Not really.

    Jen> For example, I'd like to set it to cr/lf (okay, that's eol
    Jen> characters) when reading a file (DOS text) and set it to just cr
    Jen> when writing out (Mac). Is there a way to do this?

    Sure. Open the input file in Universal newline mode (add "U" to the open
    flags) then write it in binary mode, appending the '\r' character yourself.
    Universal newline mode is new in 2.3 however. You can always open the input
    file in binary mode and explicitly strip any trailing \r\n pairs.

    inf = open("somedosfile", "rb")
    outf = open("somemacfile", "wb")
    for line in inf.read().split("\r\n"):
    outf.write(line+"\r")
    inf.close()
    outf.close()

    or, if you're running 2.3:

    inf = open("somedosfile", "rU")
    outf = open("somemacfile", "wb")
    for line in inf:
    if line.endswith("\n"):
    line = line[:-1]
    outf.write(line+"\r")
    inf.close()
    outf.close()

    Something like that should start you in the right direction.

    Skip
    Skip Montanaro, Jul 11, 2003
    #1
    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. jennyw
    Replies:
    0
    Views:
    315
    jennyw
    Jul 11, 2003
  2. Ben Fairbank
    Replies:
    2
    Views:
    5,405
  3. john san
    Replies:
    19
    Views:
    730
    Diez B. Roggisch
    Feb 18, 2005
  4. tomhr
    Replies:
    27
    Views:
    1,402
    Mike Wahler
    Jan 12, 2006
  5. January Weiner

    Reading Mac / Unix / DOS text files

    January Weiner, Feb 21, 2006, in forum: Perl Misc
    Replies:
    23
    Views:
    300
    January Weiner
    Feb 27, 2006
Loading...

Share This Page