File handling

A common requirement in programming is to be able to read from or write to a file. This allows a program to read a large amount of data, look at a configuration file, or write data to a log or report for further study. To use file handling you use the open() function.  This takes the format:

variable_to_store_file_contents = open("name_of_file", "XY")

Where X is one of:

ValueMeaning
rRead from a file. Gives an error if the file does not exist.
wWrite to a file. Creates the file if it does not exist.
aAppends onto a file. Creates the file if it does not exist.
xCreates a file. Gives an error if the file already exists
r+Reading and writing to a file. Gives an error if the file does not exist.
w+Reading and writing to a file. Creates a file if it does not exist.
a+Reading and writing to a file. Creates the file if it does not exist.

And Y is one of:

ValueMeaning
tText file
bBinary file (images, videos, etc)

The default modes are r and t. Reading a text file. You can omit these values if that is what you are trying to do. All three of the following commands are the same:

input_file = open("data.txt")
input_file = open("data.txt", "r")
input_file = open("data.txt", "rt")

Writing to a file will delete anything currently there so take care when using it and consider appending instead.

Once you have finished using a file you should close the file handler by using the close() function.

input_file = open("data.txt")
# Carry out operations
input_file.close()

If file handlers should always be closed, how do you avoid problems if an error occurs in the program before the close() function is called? You should use the with keyword. The with keyword automatically closes the file handler when the operations are finished. It also closes it, should an exception occur.

with open("data.txt") as input_file:
    # Carry out operations
Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.