By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

clarification on open file modes

P: n/a
Does a py script written to open and read binary files on Windows affect
files on a Linux or Mac machine in a negative way? My concern is
portability and safety. I want scripts written within Windows to work
equally well on Linux and Mac computers.

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()

How can a simple open in read mode corrupt data???
Jan 5 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
At Thursday 4/1/2007 23:46, tubby wrote:
>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()

How can a simple open in read mode corrupt data???
You can't corrupt *that* file if you only open it. But if you *read*
it and process the input data, you'll get some garbage. And if you
write such data (to the same file or another one), it will be corrupted.
Using "rb" or "wb" for binary files won't do any harm on systems
where it doesn't matter, and it's the right way on systems where it does.
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 5 '07 #2

P: n/a
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
Jan 7 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.