Working with Files in Python

To work with a file, you must open it using a special built-in function:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Opens a file and returns an object representing it.

File Opening Modes
ropen a file for reading
wopen a file for writing; the file content is deleted. If the file does not exist, a new one is created
xopen a file for writing if the file does not exist. If the file exists, an exception is raised
bopen a file in binary mode
topen a file in text mode
+open a file for reading and writing

File Object Methods

file.read (size)

Reads and returns information from the file. If the optional size parameter is specified, it returns only the specified number of characters/bytes.

file.write (content)

Writes information to the file.

file.tell ()

Returns the current pointer position within the file.

file.seek (position, from_what=0)

Moves the pointer to the specified position. The first argument is the number of positions to move the pointer. If this argument is positive, the pointer moves to the right; if negative, to the left.

The second, optional argument is from_what. It specifies where to move the pointer from: 0 — from the beginning of the file, 1 — from the current position, and 2 — from the end of the file. By default, this argument is 0.

file.close ()

Closes the file. You must call this method after finishing work with the file.