File operations are one of the most common features of programming languages. Python, like many other scripting syntaxes, simplifies the method in which files are used. This article discusses both reading and writing files.
Opening a file
Before a file can be written to or read from it must first be opened.
w mode for instance it will not exist and thus cause an error when trying
to write to it. When a file is opened with the w+ mode it will create
the file first and then open it.
Once a file is finished with it should be closed.
The following table shows the read modes that can be used:
| Mode | Description |
|---|---|
| r | Open an existing file for standard reading |
| r+ | Opens a file for standard reading and writing |
| w | Opens an existing file for standard writing |
| w+ | Opens a file for standard reading and writing. Also if the file does not exist, it attempts to create it. |
| a | Opens an existing file for writing with the file pointer at the end of the file. |
| a+ | Opens a file for reading and writing with the file pointer at the end of the file. |
These modes are used in conjunction with the open method:
# Open the file test.txt in read mode, if it doesn't exist then create it file = open("test.txt", "r+") file.close()
Now that the file is open the next step is to read it.
Reading a text file
Python provides a very simple method of reading text files using the
read chained method:
# Open the file test.txt in read mode file = open("test.txt", "r") print(file.read()) file.close()
And for reading the whole file:
# Open the file test.txt in read mode file = open("test.txt", "r") for line in file: print(line) file.close()
Writing to a text file
Writing to a text file couldn't be simpler in Python. Once the file object
has been opened it is simple enough to just write to it using the
write chained method:
# Open the file test.txt in write mode file = open("test.txt", "w+") file.write("Test text") file.close()
This will write just one line of text. To write multiple lines a Python list
is used to hold those lines and the writelines method is used instead:
# Open the file test.txt in write mode lines = ["Test 1", "Test 2"] file = open("test.txt", "w+") file.writelines(lines) file.close()
- Change the filename used in one of the examples and observe what happens.
- Modify the text written to the file by the
writemethod. - Add an additional line to the list used by
writelines. - Experiment with different file modes such as
"r","w"and"a".
Rewrite the program so that it creates a file called notes.txt and writes your name to it.
file = open("notes.txt", "w+") file.write("Jamie") file.close()
Modify the following program so that it reads from a different file.
file = open("test.txt", "r") print(file.read()) file.close()
Extension challenge: Ask the user to enter their name, write it to a file, close the file, reopen it and display the contents on the screen.
