clarification on open file modes

Stefan Schwarzer sschwarzer at sschwarzer.net
Sun Jan 7 02:45:57 CET 2007


On 2007-01-05 03:46, tubby wrote:
> Is this the safest, most portable way to open files on any platform:
>
> fp = open(file_name, 'rb')
> fp.close()
>
> I understand that doing the following on Windows to a binary file (a
> jpeg or exe files for example) can cause file corruption, is that correct?
>
> fp = open(file_name, 'r')
> fp.close()

Rule of thumb: If the file is a text file (usually has a concept
of "text lines"), read and write it in text mode (without "b" in
the mode argument). So line endings will be converted, so that
your Python code can process the text data identically on all
platforms. On the other hand, if you process binary files (as you
mention, for example jpg or exe files), read and write them in
binary mode, so the data won't be corrupted.

> How can a simple open in read mode corrupt data???

You won't corrupt the data in the file, but you will kind of
corrupt the data that arrives in your program.

Stefan



More information about the Python-list mailing list