Common File Methods

The Python file object supports the methods shown in the following list:

  • read()— read in data from the file

  • readline()— read a line of data from a file

  • readlines()— read all the lines in the file and return them as a tuple of strings

  • write()— write data to a file

  • writelines()— write a tuple of lines to a file

  • seek()— move to a certain point in a file

  • tell()— determine the current location in the file

This is only a partial list. You can read about other file object methods in the Python documentation.

A Little Review

You can get a list of methods that a file object supports by using the dir() command like this:

 >>> file = open("\\dat\\hello.txt") >>> dir (file) ['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name',  ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.