open(filename[, mode[, bufsize]])
Returns a new file object (see type-file). The first two arguments are the
same as for stdio's fopen(): filename is the file name
to be opened, mode indicates how the file is to be opened:
'r' for reading, 'w' for writing (truncating an
existing file), and 'a' opens it for appending (which
on some Unix systems means that all writes append
to the end of the file, regardless of the current seek
position).
Modes 'r+', 'w+' and 'a+'
open the file for updating (note that 'w+' truncates
the file). Append 'b' to the mode to open the file in
binary mode, on systems that differentiate between binary and text
files (else it is ignored). If the file cannot be opened, IOError is raised.
In addition to the standard fopen() values mode may be
'U' or 'rU'. If Python is built with universal
newline support (the default) the file is opened as a text file,
but lines may be terminated by any of '\n', the Unix
end-of-line convention, '\r', the Macintosh convention
or '\r\n', the Windows convention. All of these
external representations are seen as '\n' by the
Python program. If Python is built without universal newline
support mode 'U' is the same as normal text mode. Note
that file objects so opened also have an attribute called newlines
which has a value of None (if
no newlines have yet been seen), '\n',
'\r', '\r\n', or a tuple containing all the
newline types seen.
If mode is omitted, it defaults to 'r'. When
opening a binary file, you should append 'b' to the
mode value for improved portability. (It's useful even on systems
which don't treat binary and text files differently, where it
serves as documentation.) The optional bufsize argument specifies
the file's desired buffer size: 0 means unbuffered, 1 means line
buffered, any other positive value means use a buffer of
(approximately) that size. A negative bufsize means to use the
system default, which is usually line buffered for tty devices and
fully buffered for other files. If omitted, the system default is
used.
Note: Specifying a buffer size currently has no effect on systems that don't have setvbuf(). The interface to specify the buffer size is not done using a method that calls setvbuf(), because that may dump core when called after any I/O has been performed, and there's no reliable way to determine whether this is the case.
The file constructor is new in Python 2.2 and is an alias for open. Both spellings are equivalent. The intent is for open to continue to be preferred for use as a factory function which returns a new file object. The spelling, file is more suited to type testing (for example, writing "isinstance(f, file)").