Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.6Reading and writing files in Python

Part 3.6Reading and writing files in Python

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.

Opening a file is not the same as reading a file. When a file is opened using the 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:

Python
# 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:

Python
# Open the file test.txt in read mode
file = open("test.txt", "r")
print(file.read())
file.close()
    

And for reading the whole file:

Python
# 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:

Python
# 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:

Python
# Open the file test.txt in write mode
lines = ["Test 1", "Test 2"]
file = open("test.txt", "w+")
file.writelines(lines)
file.close()
    
Feedback 👍
Comments are sent via email to me.