"\n" in ASCII-file

Gilles Lenfant glenfant at NOSPAM.bigfoot.com
Fri Jul 18 17:32:22 CEST 2003


"Martin P" <martin_p at despammed.com> a écrit dans le message de news:
bf8j40$bj4e4$1 at ID-108519.news.uni-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





More information about the Python-list mailing list