A program can be short or long. It can have several functionalities in it, such as asking input from a user and then giving an output. Eventually, when the program terminates, you will lose your results if you don’t save them. That’s why reading and writing files in Python comes in handy.
Related: JSON with Python – Reading & Writing (With Examples)
Similarly, we may also need to read data or information in our code from an external source. Let’s say you want your program to read data from a text file. That’s why the data needs to be in a format that you can use your application to read later.
In programming, we use files to store data. And there are two types of files:
1. Text files: The text files are simple files used for storing standard text. A text file has a .txt extension, and which you can create easily using a notepad.
2. Bin files: The bin files store data in binary format. A bin file has a .bin extension.
We can use such files our programs using file operations that Python provides. So in this article, we will discuss how to perform file operations and learn the nuts and bolts of reading and writing files in Python.
Video tutorials on reading and writing files are also available from LinkedIn Learning.
Check out this course:
File Operations in Python
There are two types of file operations when it comes to reading and writing files in Python – Read and Write.
1. Read operation: The read operation reads a file. Suppose we have a text file, and we want to use the text in our program. Then, we have to perform the read operation.
2. Write operation: The write operation writes on a file. When a program terminates, every data associated with it is lost. If we want to store the data, we can use the write operation to save it in a new file, or to an existing one.
You may like:
- The Ultimate Python Cheat Sheet – An Essential Reference for Python Developers
- Building a Web App with Python – Getting Started With Flask
Access modes
The access modes determine why a file is open and what kind of operation we can perform. These modes also define their location.
One of the key concepts that you have to understand about reading and writing files in Python are the access modes.
Python has six access modes for accessing files. Let’s discuss each of them with the help of examples.
Read-only
The read-only mode reads a file, and it is denoted by “r.”
In simple words, this mode opens an existing file. Python has an in-built function called open(), which we can use to open our file. Python then places a stream at the beginning of the text to start reading from the very first character.
Think of a stream as a general pointer that points to a particular location on our file.
Let’s see how to use the open() function to read a file in Python.
file1 = open("sample1.txt", "r")
print(file1)
file1.close()
The open() function takes two parameters – location of the file and the access mode.
In the end, we have a close() function. It will deallocate the memory assigned to open the file. Also, reset the access mode.
If the file is present in the same directory in which the program exists, then we can also write the file, else we have to specify the full path.
Remember, r denotes the read-only mode.
The file1 is the object for sample1.txt.
To read the data, Python provides three functions.
1. read()
The read() function reads a file and returns a string.
If there is no argument, then it will read the entire file and give you an output.
This is a sample file.
This is a sample file.
This is a sample file.
This is a sample file.
This is a sample file.
>>>
Moreover, if the argument is a number, the function will read only that many characters.
file1 = open("sample1.txt", "r")
print(file1.read())
file1.close()
The read() function by itself will read the entire file.
Let’s read the first ten characters.
file1 = open("sample1.txt", "r")
print(file1.read(10))
file1.close()
Output:
This is a
>>>
2. readline()
The readline() function is similar to the read() function, but it only reads one line.
file1 = open("sample1.txt", "r")
print("readline: ",file1.readline(40))
print("read: ",file1.read(40))
file1.close()
Output:
readline: This is a sample file.
read: This is a sample file.
This is a sample
>>>
Both read() and readline() functions should read first 40 characters. Let’s see what happens.
While the read() function successfully reads the first 40 characters, the readline() function only reads the first line.
3. readlines()
The readlines() function returns a list of lines in the file.
file1 = open("sample1.txt", "r")
print(file1.readlines())
file1.close()
Output:
['This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n'
>>>
Additionally, the read-only mode is the default mode in Python. As you use the open() function, it will still work without passing the r.
Read & Write
The read and write mode reads and then writes on a file. It is denoted by r+.
The content that we are trying to add or append will be at the end of a file.
file1 = open("sample2.txt", "r+")
print("Before write: ", file1.read())
file1.write("Hello World!")
file1.seek(0)
print("After write: ", file1.read())
file1.close()
Output:
Before write: This is a sample.
After write: This is a sample. Hello World!
>>>
Let’s understand the above code step by step.
First, the code is opening the file using the open() function. We here have the read and write mode, which is r+.
Then, there is the write() function to write on the already opened file. We then used the seek() function and provided 0 as the argument.
file1.seek(0)
0 means the stream will move to the first character.
At last, there is the read() function to read the file.
Write-only
The write-only mode allows us to write on a file. This mode has the denotation w.
file1 = open("sample1.txt", "r")
print("Before: ", file1.read())
file1.close()
file1 = open("sample1.txt", "w")
file1.write("Hello World!")
file1.close()
file1 = open("sample1.txt", "r")
print("After: ", file1.read())
file1.close()
Output:
Before: This is a sample
After: Hello world!
>>>
We cannot use any other function to read the file when the access mode is write-only.
After the write operation, the close() function allows us to open the file again using the read-only mode.
Now, let’s try to read with the write-only mode.
file1 = open("sample1.txt", "w")
file1.write("Hello World!")
print(file1.read())
file1.close()
It will throw an error:
Traceback (most recent call last):
File "D:\example.py", line 5, in <module>
print(file1.read())
io.UnsupportedOperation: not readable
>>>
So, when the mode is write-only, we cannot read the file.
Write & Read
Like read and write mode, the write and read mode works to read and write on a file. It has a denotation of w.
But there are a couple of differences. And try to understand them carefully.
The read and write mode throws an error if the file does not exist while write and read will create a new file if it does not exists.
file1 = open("demo.txt", "r+")
file1.write("Hello World!")
file1.seek(0)
print(file1.read())
The above code uses the read and write mode to open a file named demo.txt. You can see that the file does not exist.
Output:
Traceback (most recent call last):
File "D:\example.py", line 5, in <module>
file1 = open("demo.txt", "r+")
FileNotFoundError: [Errno 2] No such file or directory: 'demo.txt'
>>>
It throws an error.
Now let’s try the same with write and read mode.
file1 = open("demo.txt", "w+")
file1.write("Hello World!")
file1.seek(0)
print(file1.read())
Output:
Hello World!
>>>
It will create a new file and writes on it.
The write and read mode overwrites the content of the existing file.
After the above example, demo.txt has “Hello World!”.
file1 = open("demo.txt", "w+")
file1.write("Say Hi")
file1.seek(0)
print(file1.read())
The write operation will overwrite “Hello World!” with “Say Hi.”
Append-only
The append-only mode appends characters at the end of the content. It is denoted by a.
file1 = open("sample1.txt", "r")
print("Before: ", file1.read())
file1.close()
file1 = open("sample1.txt", "a")
file1.write("Hello World!")
file1.close()
file1 = open("sample1.txt", "r")
print("After: ", file1.read())
file1.close()
Output:
Before: This is a sample.
After: This is a sample.Hello World!
>>>
While the write-only overwrites the content, the append-only mode appends at the end of a line or a character.
The append mode will also throw an error if we try to read the file.
file1 = open("sample1.txt", "a")
file1.write("Hello World!")
print(file1.read())
file1.close()
Output:
Traceback (most recent call last):
File "D:\example.py", line 5, in <module>
print(file1.read())
io.UnsupportedOperation: not readable
>>>
Append & Read
The append and read mode is similar to the append-only but with one exception. It can also read the file.
file1 = open("sample1.txt", "a+")
file1.seek(0)
print("Before:", file1.read())
file1.write("Hello World!")
file1.seek(0)
print("After: ", file1.read())
file1.close()
It will not throw an error:
Before: This is a sample.
After: This is a sample.Hello World!
>>>
Points to Remember
There are few functions and six access modes in total for reading and writing files in Python.
Let’s discuss some of the essential points you should keep in mind while performing read and write operations in Python:
1. Always be careful while specifying the access mode.
2. Always close the file using the close() function. It will deallocate the memory.
3. Use the read() and readline() function carefully. Remember, the readline() function will only read the first line.
4. The read and write mode do not create a new file while the write and read mode does.
5. The write mode will overwrite the existing content of a file. It is similar in the case of write and read mode.
6. The append mode will append at the last of the content. It is similar in the case of append and read mode.
7. Always use the seek() function with 0 as the argument if it is required to move the stream to the beginning.
Conclusion
Reading and writing files in Python are a bit complex. It is necessary to understand the access mode properly if you want to understand how read and write operations work.
Read:
- Data Structures & Algorithms in Python – Introduction to Hash Tables
- Data Structures & Algorithms in Python – Recursion
I recommend that you go over this tutorial again and again until you are clear with the modes. This may take a while.
To learn more on reading and writing files in Python check out these courses from LinkedIn Learning:
- Python: XML, JSON, and the Web
- Processing and Interchanging JSON Data
- Introduction to Web APIs
- Learn API Documentation with JSON and XML
Also, remember that you can sign up for a LinkedIn Learning account for absolutely free.
Click here for a free account.
Is there any part of this tutorial that is confusing you? Do you like reading and writing files in Python? Are there any mistakes in this article? Comment below.