Next / Previous / Contents / TCC Help System / NM Tech homepage

9. Input and output: File objects

To open a file:

f = open(name[,mode[,bufsize]]])

This function returns a file object. The name is the file's pathname. The bufsize argument, if given, is used to specify the buffer size (but this is not usually necessary). The mode argument is a string with this syntax:

"access[+][b]"

where access is r for read access (the default), w for write access, and a for append. The + flag specifies update access, and b forces binary mode.

Methods defined on file objects include:

f.read()

Read the entire file f and return it as a string.

f.read(n)

Read the next n characters from file f. If the file is exhausted, it returns an empty string (""); if fewer than n characters remain, you get all of them.

f.readline()

Returns the next line from f, including its line terminator, if any. Returns an empty string when the file is exhausted.

f.readlines()

Read all the lines from file f and return them as a list of strings, including line termination characters.

f.write(s)

Write string s to file f.

f.writelines(L)

Write a list of strings L to file f.

f.seek(p[,w])

Change the file position. The value of w determines how p is used:

  • 0: Set the position to p; this is the default.

  • 1: Move the position forward p bytes from its current position.

  • 2: Set the position to p bytes before the end of file.

f.truncate([p])

Remove any contents of the file past position p, which defaults to the current position.

f.tell()

Returns the current file position.

f.flush()

Flush the buffer, completing all transactions against f.

f.isatty()

Predicate: Is this file a terminal?

f.close()

Close file f.