O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Files and File Objects

The built-in function open(name [,mode [,bufsize]]) opens and creates a file object, as shown here:

f = open('foo')        # Opens 'foo' for reading
f = open('foo','r')    # Opens 'foo' for reading (same as above)
f = open('foo','w')    # Open for writing

Although less common, files can also be created by calling the file object constructor, which is identical to open(). For example:

f = file('foo')        # Opens 'foo' for reading
f = file('foo','w')    # Open for writing

The file mode is ‘r’ for read, ‘w’ for write, or ‘a’ for append. The mode character can be followed by ‘b’ for binary data, such as ‘rb’ or ‘wb’. This is optional on UNIX, but it’s required on Windows and should be included if you are concerned about portability. In addition, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required