P
P
Python Classroom
Search…
⌃K

Files

Opening a File

Open a File for Reading
infile = open("file.txt", "r")
Open a File for Writing
outfile = open("file.txt", "w")
Open a File for Appending
outfile = open("file.txt", "a")
Closing a File
file.close()
Write to a File
file.write()

Open a File for reading

To open a file for reading, provide the name of the file as the first argument to the open function and the string "r" as the second argument. When opening a file for reading, the file must exist or an exception will occur.
infile = open("input.txt", "r")

Open a File for writing

To open a file for writing, provide the name of the file as the first argument to the open function and the string "w" as the second argument. If the output file already exists, it is emptied before the new data is written into it. If the file does not exist, an empty file is created.
outfile = open("output.txt", "w")

Open a File for appending

To open a file for appending, provide the name of the file as the first argument to the open function and the string "a" as the second argument. If the file does not exist, an empty file is created.
file = open("output.txt", "a")

Closing a File

When you are done processing a file, make sure you close the file using the close method. If your program exists without closing a file that was opened for writing, some of the output may not be written to the disk file.
file.close()

Reading a File

An easy way to read the contents of a file is to use a for loop.
for line in file:
# process the line.
Other ways include using the read(), readline(), and readlines() methods.
file.read()
Will read the entire contents of a file as a string.
file.readline()
Will read a single line from the file, up to and including the first instance of the newline character.
file.readlines()
Will read the entire contents of a file into a list where each line of the file is a string and is an element in the list.

Writing a File

You can write text to a file that has been opened for writing. This is done by applying the write method to the file object.
You can write text to a file with the print function. Supply the file object as an argument with name file, as follows:
print("Hello, World!", file=outfile)
outfile.write("Hello, World!\n")