next up previous contents
Next: File Object Variables Up: File Objects Previous: ``Printing'' to a File   Contents

Other Methods

The close method can be used to close a file after you are done reading or writing to it. While python will automatically close open files when you try to re-open them, and at the end of your program, it still is a good idea to explicitly close files when you are done using them.

When using buffered input or output, it may occasionally be useful to use the flush method to insure that the file's buffer is emptied.

The tell method returns the current offset of the file object in bytes. This is the location in the file where the next operation (read or write) will take place. To set the file pointer to a particular offset within the file, use the seek method. This method takes two arguments. The first is the desired offset (in bytes), and the second argument, which is optional, tells the system if the offset is from the beginning of the file (an argument of 0, the default), from the current position (an argument of 1) or from the end of the file (an argument of 2). A read or write operation following a call to seek will then be operating at the location specified. While there is no explicit ``rewind'' method provided, you can set the file offset to 0 for a file object f with the call

f.seek(0)
effectively setting the file back to the beginning.

The truncate method accepts a number of bytes as its argument and changes the length of the file being operated on to that many bytes. If the file is shorter than the number of bytes specified, it will be padded with null characters (binary zeroes, not blanks).


next up previous contents
Next: File Object Variables Up: File Objects Previous: ``Printing'' to a File   Contents
Phil Spector 2003-11-12