clarification on open file modes

T

tubby

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???
 
G

Gabriel Genellina

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
 
S

Stefan Schwarzer

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top