Re: "\n" in ASCII-file

Discussion in 'Python' started by Gilles Lenfant, Jul 18, 2003.

  1. "Martin P" <> a écrit dans le message de news:
    bf8j40$bj4e4$-berlin.de...
    > Hello,
    >
    > for a short exercise-program I have to read the lines in an ASCII-file.
    >
    > But every line has a new-line-feed ("\n") at the end of the line. (The
    > ASCII-file was made with Windows Notepad).
    > Is this only because I used Windows (and Notepad)?
    >
    > And... is there any special method to read lines from a file without "\n"?
    >
    > Bye,
    > Martin
    >
    >


    3 ways (among others...) :

    1/ You just want to remove all EOL characters and keep other blank trailing
    characters:

    f = open("myfile.txt", "r")
    while 1:
    line = f.readline()
    if not line:
    break
    line = line.replace("\r", "")
    line = line.replace("\n", "")
    # process the line your way...

    2/ You want to remove all EOL characters other blank trailing characters:

    f = open("myfile.txt", "r")
    while 1:
    line = f.readline()
    if not line:
    break
    line = line.rstrip()
    # process the line your way...

    3/ You got python 2.3 (not me) and there's a new mode for reading the lines
    without the EOL character(s). Read the manual at the "file object" chapter,
    or "open" in the builtins chapter.

    --Gilles
    Gilles Lenfant, Jul 18, 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. TOXiC
    Replies:
    5
    Views:
    1,249
    TOXiC
    Jan 31, 2007
  2. James O'Brien
    Replies:
    3
    Views:
    251
    Ben Morrow
    Mar 5, 2004
  3. Alextophi
    Replies:
    8
    Views:
    509
    Alan J. Flavell
    Dec 30, 2005
  4. bruce
    Replies:
    38
    Views:
    273
    Mark Lawrence
    Nov 1, 2013
  5. MRAB
    Replies:
    0
    Views:
    96
Loading...

Share This Page