Linux/Unix > Python Essential Reference, Second Edition > 9. Input and Output > Files | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105084124007242194071231

### Files

The built-in function `open(``name` `[,``mode` `])` opens and creates files, as shown here:

    f = open('foo')        # Opens 'foo' for reading
    f = open('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 required on Windows, and should be included if you’re concerned about portability. In addition, a file can be opened for updates by supplying a plus (`+`) character, such as `'r+'` or `'w+'`. When a file is opened for update, you can perform both input and output, as long as all output operations flush their data before any subsequent input operations. If a file is opened using `'w+'` mode, its length is first truncated to zero.

`open()` returns a file object that supports the methods shown in Table 9.1.

##### Table 9.1. File Methods

Method | Description
--- | ---
`f` `.read([``n` `])` | Reads at most `n` bytes.
`f` `.readline([``n` `])` | Reads a single line of input up to `n` characters. If `n` is omitted, reads the entire line.
`f` `.readlines()` | Reads all the lines and returns a list.
`f` `.xreadlines()` | Returns an opaque sequence object where each iteration reads a new line from the file.
`f` `.write(``s` `)` | Writes string `s` .
`f` `.writelines(``l` `)` | Writes all strings in list `l` .
`f` `.close()` | Closes the file.
`f` `.tell()` | Returns the current file pointer.
`f` `.seek(``offset` `[,` `where` `])` | Seeks to a new file position.
`f` `.isatty()` | Returns `1` if `f` is an interactive terminal.
`f` `.flush()` | Flushes the output buffers.
`f` `.truncate([``size` `])` | Truncates the file to at most `size` bytes.
`f` `.fileno()` | Returns an integer file descriptor.
`f` `.readinto(``buffer` `,``nbytes` `)` | Read `nbytes` of data into a writable buffer object.

The `read()` method returns the entire file as a string unless an optional `length` parameter is given specifying the maximum number of bytes. The `readline()` method returns the next line of input, including the terminating newline; the `readlines()` method returns all the input lines as a list of strings. The `readline()` method optionally accepts a maximum line length `n` . If a line longer than `n` bytes is read, the first `n` bytes are returned. The remaining line data is not discarded and will be returned on subsequent read operations. Both the `readline()` and `readlines()` methods are platform-aware and handle different representations of newlines properly (for example, `'\n'` versus `'\r\n'`). The `xreadlines()` method returns a special opaque sequence object that allows the lines of a file to be read using iteration instead of first being read entirely into memory, as with the `readlines()` method. For example:

    for line in f.xreadlines():
        # Do something with line
        ...

The `write()` method writes a string to the file, and the `writelines()` method writes a list of strings to the file. In all these cases, the string can contain binary data, including embedded null characters.

The `seek()` method is used to randomly access parts of a file given an `offset` and a placement rule in `where` . If `where` is `0` (the default), `seek()` assumes that `offset` is relative to the start of the file; if `where` is `1`, the position is moved relative to the current position; and if `where` is `2`, the offset is taken from the end of the file. The `fileno()` method returns the integer file-descriptor for a file and is sometimes used in low-level I/O operations in certain library modules. On machines that support large files (greater than 2GB), the `seek()` and `tell()` methods use long integers. However, enabling such support may require a reconfiguration and recompilation of the Python interpreter.

File objects also have the data attributes shown in the following table.

Attribute | Description
--- | ---
`f` `.closed` | Boolean value indicates the file state: `0` if the file is open, `1` if closed.
`f` `.mode` | The I/O mode for the file.
`f` `.name` | Name of the file if created using `open()`. Otherwise, it will be a string indicating the source of the file.
`f` `.softspace` | Boolean value indicating whether a space character needs to be printed before another value when using the `print` statement. Classes that emulate files must provide a writable attribute of this name that’s initially initialized to zero.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.