[Tutor] Reading only a few specific lines of a file
Kent Johnson
kent37 at tds.net
Sun May 25 21:32:32 CEST 2008
Forwarding to the list with my reply...
On Sun, May 25, 2008 at 2:20 PM, Chester <wxpythoner at gmail.com> wrote:
> Python uses \n as the newline character (which is a UNIX/Linux newline
> character). I see you have Python for Windows installed and running it on
> the Windows OS. The file objectconfig.txt has the Windows newline character
> \r\n at the end of each physical line, which confuses the Python parser. I
> think you need to look at the linesep function of the os module; that is,
> use os.linesep (check how to use it) and you should be good. ;)
Umm...no.
\n does double-duty, in a way. It is the linefeed character, and it
represents a newline.
On Unix-like OSes such as Unix, Linux and MacOS X the newline
character is a single linefeed so there is no difference between these
two meanings.
Windows uses two characters - carriage return + line feed - to
represent a newline. When you read a text file in Python on Windows,
the CRLF pairs are converted to a single LF char, or \n. So in this
sense \n does represent a newline in a portable fashion.
Note that this has nothing to do with the Python *parser*, which reads
Python source files. It is the Python runtime that makes the
translation.
One every platform, when you read lines from a file using "for line in
f", f.readline() or f.readlines(), the newline character is included
in the returned line. This is the source of the OP's problem, not any
confusion on the part of the parser or the runtime.
Kent
PS Please use Reply All to reply to the list.
More information about the Tutor
mailing list