Table B.11 lists the built-in methods and data attributes of file objects.
Table B.11. Methods for File Objects
File Object Attribute | Description |
---|
file.close() | Closes file |
file.fileno() | Returns integer file descriptor (FD) for file |
file.flush() | Flushes internal buffer for file |
file.isatty() | Returns true if file is a tty-like device and False otherwise |
file.next[a]() | Returns the next line in the file [similar to file.readline()] or raises Stop Iteration if no more lines are available |
file.read(size=-1) | Reads size bytes of file, or all remaining bytes if size not given or is negative, as a string and return it |
file.readinto[b](buf, size) | Reads size bytes from file into buffer buf (unsupported) |
file.readline(size=-1) | Reads and returns one line from file (includes line-ending characters), either one full line or a maximum of size characters |
file.readlines(sizhint=0) | Reads and returns all lines from file as a list (includes all line termination characters); if sizhint given and > 0, whole lines are returned consisting of approximately sizhint bytes (could be rounded up to next buffer's worth) |
file.xreadlines[c]() | Meant for iteration, returns lines in file read as chunks in a more efficient way than readlines() |
file.seek(off, whence=0) | Moves to a location within file, off bytes offset from whence (0 == beginning of file, 1 == current location, or 2 == end of file) |
file.tell() | Returns current location within file |
file.truncate(size=file.tell()) | Truncates file to at most size bytes, the default being the current file location |
file.write(str) | Writes string str to file |
file.writelines(seq) | Writes seq of strings to file; seq should be an iterable producing strings; prior to 2.2, it was just a list of strings |
file.closed | true if file is closed and False otherwise |
file.encoding[d] | Encoding that this file useswhen Unicode strings are written to file, they will be converted to byte strings using file.encoding; a value of None indicates that the system default encoding for converting Unicode strings should be used |
file.mode | Access mode with which file was opened |
file.name | Name of file |
file.newlines[d] | None if no line separators have been read, a string consisting of one type of line separator, or a tuple containing all types of line termination characters read so far |
file.softspace | 0 if space explicitly required with print, 1 otherwise; rarely used by the programmergenerally for internal use only |