file

File objects are implemented using C’s <stdio.h> package and can be created with the built-in file() and open() functions. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

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 are viewed as a sequential stream of bytes. A file is terminated with an end of file marker (EOF). When a file is opened a file object is associated with it.

By default, there are three files initialized when the script execution starts - sys.stdin, sys.stdout and sys.stderr. They correspond to the interpreter’s standard input, output and error streams.

Constructors

file
Returns a file object.
open
Returns a file object.

Methods

Reading

read
Returns specified amount of bytes from the file.
readline
Reads one entire line from the file.
readlines
Returns a list containing lines from the file.
xreadlines
Returns an iterator over the lines of the file.
next
Returns a next line from the file.

Writing

write
Writes a string to the file.
writelines
Writes a sequence of strings to the file.
flush
Flushes the write buffers of the file.

File Position

tell
Returns the file’s current position.
seek
Sets the file’s current position.

Other

close
Flushes and closes the file.
fileno
Returns the integer “file descriptor”.
truncate
Truncates the file’s size.
isatty
Returns True if the file is if the stream is interactive (i.e., connected to a terminal/tty device).

Properties

name
Returns the name of the file.
mode
Returns the I/O mode for the file.
encoding
Returns the encoding of the file.
closed
Returns a Boolean stating whether the file is closed.
errors
Returns the Unicode error handler used along with the encoding.
newlines
Return type of newlines encountered while reading the file.
softspace
Returns a Boolean that indicates whether a space character needs to be printed before another value when using the print statement.