Next: Internal Objects Prev: The Null Object Up: Other Built-in Types Top: Top

2.1.7.7. File Objects.

File objects are implemented using C's stdio package and can be created with the built-in function open() described under Built-in Functions below.

When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.

Files have the following methods:

close () -- Method on file
Close the file. A closed file cannot be read or written anymore.
flush () -- Method on file
Flush the internal buffer, like stdio's fflush().
isatty () -- Method on file
Return 1 if the file is connected to a tty(-like) device, else 0.
read (size) -- Method on file
Read at most size bytes from the file (less if the read hits EOF or no more data is immediately available on a pipe, tty or similar device). If the size argument is omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.)
readline () -- Method on file
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). An empty string is returned when EOF is hit immediately. Note: unlike stdio's fgets(), the returned string contains null characters ('\0') if they occurred in the input.
readlines () -- Method on file
Read until EOF using readline() and return a list containing the lines thus read.
seek (offset, whence) -- Method on file
Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value.
tell () -- Method on file
Return the file's current position, like stdio's ftell().
write (str) -- Method on file
Write a string to the file. There is no return value.