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

17.1. Methods on file objects

Use these methods on an open file instance F.

F.close()

Close file F. Any unwritten data in the buffer will be flushed. No further operations will be allowed on the file unless it is reopened with the open() function.

F.flush()

For buffered files, you can use this method to make sure that all data written to the file has been physically transmitted to the storage medium. Closing a file will also flush the buffers. Avoid using this method unless you really need it, as it may make your program less efficient.

F.isatty()

A predicate that tests whether F is a terminal; “tty” is an ancient term that originally meant “Teletype”, but has come to mean any terminal or simulated terminal.

F.read(n )

Read the next n characters from F and return them as a string.

If there are fewer than n characters remaining after your current position, you will get all remaining characters. If you are at the end of the file, you will get back an empty string ('').

The argument is optional. If omitted, you will get the entire remaining contents of the file as a string.

F.readline(maxlen)

Read the next text line from F and return it as a string, including the line terminator if any.

If you need to limit the maximum size of incoming lines, pass that size limit as the optional maxlen argument. The default is to return a line of any size (subject to memory limitations). If the line exceeds maxlen, the file position will be left pointing to the first unread character of that line.

F.readlines()

Read all remaining lines from F and return them as a list of strings, including line terminator characters if any.

F.seek(offset, whence)

Change the file's current position. The value of whence determines how the offset value is used to change the position:

  • 0: Set the position to offset bytes after the beginning of the file.

  • 1: Move the current position offset bytes toward the end of the file.

  • 2: Move the current position offset bytes relative to the end of the file.

    For example, for a file f, this operation would set the position to 4 bytes before the end of the file:

    f.seek(-4, 2)
    

F.tell()

This method returns the current file position relative to the beginning as a long value.

>>> f=open('roundtable', 'w')
>>> f.write('Bedevere')
>>> f.tell()
8L
>>> f.seek(2L)
>>> f.tell()
2L

F.truncate([pos])

Remove any contents of F past position pos, which defaults to the current position.

F.write(s)

Write the contents of string s to file F. This operation will not add terminator characters; if you want newlines in your file, include them in the string s.

F.writelines(S)

For a sequence S containing strings, write all those strings to F. No line terminators will be added; you must provide them explicitly if you want them.