safest way to open files on all platforms

R

rbt

I believe that this is the safest way to open files on Windows, Linux,
Mac and Unix, but I wanted to ask here just to be sure:

fp = file('filename', 'rb')

The 'b' on the end being the most important ingredient (especially on
Windows as a simple 'r' on a binary file might cause some sort of
corruption).

Anyway, am I right in saying this? That 'rb' is the safest way to open
files for reading and that it should work well on *all* Python supported
platforms?

Many thanks,

RBT
 
F

Fredrik Lundh

rbt said:
I believe that this is the safest way to open files on Windows, Linux, Mac and Unix, but I wanted
to ask here just to be sure:

fp = file('filename', 'rb')

The 'b' on the end being the most important ingredient (especially on Windows as a simple 'r' on a
binary file might cause some sort of corruption).

Anyway, am I right in saying this? That 'rb' is the safest way to open files for reading and that
it should work well on *all* Python supported platforms?

"rb" works on all platforms, yes. but it doesn't work well if you're reading a text file.

(when reading text files, the "U" option may also be useful. see doc for details)

</F>
 
R

rbt

Fredrik said:
:




"rb" works on all platforms, yes. but it doesn't work well if you're reading a text file.

(when reading text files, the "U" option may also be useful. see doc for details)

</F>

I'm using 'rb' in a situation where all files on the drive are opened.
I'm not checking how the file is encoded before opening it (text,
unicode, jpeg, etc.) That's why I though 'rb' would be safest.

Can 'U' be used with 'rb'? Should it be? From what I read, 'U' handles
the different ways in which the OS handles the 'end of line' on text
files, but other than that, I don't think it's useful for me.
 
F

Fredrik Lundh

rbt said:
I'm using 'rb' in a situation where all files on the drive are opened. I'm not checking how the
file is encoded before opening it (text, unicode, jpeg, etc.) That's why I though 'rb' would be
safest.

if "safest way to open files" meant "safest way to open binary files", why
didn't you say so in your first post?
Can 'U' be used with 'rb'? Should it be?

"U" is for text files, "b" is for binary files. binary files contain bytes, text
files contain text. if you're opening a file to read it as text (readline, read-
lines, iteration, etc), use "r" or "rU". if you're opening a file to read it as
binary bytes (read), use "rb".

</F>
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top