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()