\r\n or \n notepad editor end line ???
Terry Hancock
hancock at anansispaceworks.com
Mon Jun 13 19:28:32 EDT 2005
On Monday 13 June 2005 09:34 am, Steven D'Aprano wrote:
> On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote:
> > <ajikoe at gmail.com> wrote:
> >> It means in windows we should use 'wb' to write and 'rb' to read ?
> >> Am I right?
> > no.
> > you should use "wb" to write *binary* files, and "rb" to read *binary*
> > files.
> >
> > if you're working with *text* files (that is, files that contain lines of text
> > separated by line separators), you should use "w" and "r" instead, and
> > treat a single "\n" as the line separator.
>
> I get nervous when I read instructions like this. It sounds too much like
> voodoo: "Do this, because it works, never mind how or under what
> circumstances, just obey or the Things From The Dungeon Dimensions will
> suck out your brain!!!"
Actually, it's very simple. It just means that '\n' in memory maps to '\r\n' on
disk, and vice-versa. So long as you remain on Windows (or MS-DOS for
that matter).
> When you read a Windows text file using "r" mode, what happens to the \r
> immediately before the newline? Do you have to handle it yourself? Or will
> Python cleverly suppress it so you don't have to worry about it?
'\n' in memory, '\r\n' on disk.
Do the same thing on a Linux or Unix system, and it's
'\n' in memory, '\n' on disk
and on the Mac:
'\n' in memory, '\r' on disk
> And when you write a text file under Python using "w" mode, will the
> people who come along afterwards to edit the file in Notepad curse your
> name? Notepad expects \r\n EOL characters, and gets cranky if the \r is
> missing.
No, all will be well. So long as you use 'r' (or 'rt' to be explicit) and 'w'
(or 'wt').
Only use 'rb' and 'wb' if you want to make sure that what is on disk is
literally the same as what is in memory. If you write text files this way
in Python, you will get '\n' line endings.
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com
More information about the Python-list
mailing list