Python Wiki
Advertisement

General information[]

File handling is a very important aspect in Python, especially when it comes to website developing fields. Python has methods for opening, reading, creating, and closing files.

Basic Syntax[]

Open Files[]

The open() function is used to access files. The file accessed has to be stored in a variable for future uses of it.

If the file does not exist, the program will raise an error.

variable = open(filename, access-mode)

Closing files[]

The close function is used to close files and prevent further usage of them.

It's strongly advised that you close the file once you're doing using it. This is because, due to buffering, the changes made to the file may not show up until you close it.

variable = open(filename, access-mode)
variable.close()

Writing information[]

To write information to a file, we use the write-command:

write('String_to_write_to_file')

Note that with the write-command, we can only write Strings to a file, for writing more complicated structures, please check out the Pickle module.

Reading informations[]

Like the write-command, there exists the read-command:

read()

Access-mode[]

There are several different access-modes:

Access-mode Explanation
w Write-mode, overwrites data if file is non-empty
r Read-mode, read-only
a Append-mode, writes informations at the end of the file
For all of these modes there exists the same one with a '+', e.g. w+. This is read-and-write-mode.
For all of these also exists the same name with 'b', e.g. wb. This stands for binary-mode.
Advertisement