Close
Close

Python Files Handling


When a program runs, the data is in the memory but when it ends or the computer shuts down, it gets lost. To keep data permanently, we need to write it in a file.

File is used to store data. You must be using files in your electronic devices to store many things like projects, reports or even a story.

In this topic, you will learn about reading data from a file and writing data to the file using a Python program. Yes, we can do that in Python.

Suppose you have a file in your computer and you want to print the content of that file on the screen. To do that first you will open the file, then read the content of the file and then print the content. Performing such types of operations involving files is called file handling.

To perform any read or write operation on file, we first need to open the file. Let’s see how to open a file.

Python Opening a File


A file can be opened using the open() function. This function receives the filename as input and returns the file object.

Suppose you have a file named example.txt in your system. Then you can open it by writing open(“example.txt”) as shown below.

f = open("example.txt")

Here the open() function returns the file object and that file object is assigned to the variable f. Afterwards, we will be using the file object stored in f to read or write the content of the file example.txt.

We can also open a file by passing the exact path of the file to the open() function as shown below.

f = open("C:/Documents/examples/example.txt")

Python File Modes


While opening a file, we can also specify why we want to open the file. This can be done by passing a mode to the open() function. Python has the following built-in modes which are used to specify the intention of opening a file.

Mode Description
r Opens a file for reading (read-only mode). This is the default mode.
rb Opens a file for reading binary format.
r+ Opens a file for reading and writing.
rb+ Opens a file for reading and writing in binary format.
w Opens a file for writing to that file. If the file does not exist, then it creates a new file, and if the file already exists, then it overwrites the file.
wb Opens a file for writing in binary format.
w+ Opens a file for writing and reading.
wb+ Opens a file for writing and reading in binary format.
a Opens a file for appending, which means the content gets appended to the end of the file. If the file does not exist, then it creates a new file.
ab Opens a file for appending in binary format.
a+ Opens a file for appending and reading.
ab+ Opens a file for appending and reading in binary format.
x Opens a file for exclusive creation. If the file already exists, the operation fails.

If we want to open a file to read its content, we need to pass the mode r as an additional argument to the open() function using any one of the following two syntaxes.

f = open("example.txt", 'r')
f = open("example.txt", mode = 'r')

The above line of code opens the example.txt file in the read mode. This means that we will only be able to read the content from this file and won’t be able to write anything in the file. The ‘r’ mode is also the default mode, so if we don’t pass any mode to the function, then by default the ‘r’ mode is considered.

Similarly, if we want to open a file to write something in it, the w mode is passed. If we want to both read and write to a file, we can pass either r+ mode or w+ mode.

f = open("example.txt")  # equivalent to open("example.txt", 'r')
f = open("example.txt", 'w')  # opens a file to write to it
f = open("example.txt", 'r+')  # opens a file to read and write
f = open("example.txt", 'w+')  # opens a file to read and write
f = open("example.txt", 'a')  # opens a file to append data to it
f = open("example.txt", 'a+')  # opens a file to read and append data to it

It is mandatory to pass a mode to the open() function, unless you are opening a file just for reading its content (because ‘r’ is the default mode). For example, if you want to write something in a file, then you have to specify that while opening the file by passing the ‘w’ mode to the open() function.

Giving the modes rb, rb+, wb, wb+, ab and ab+ opens the file in binary mode. These are used to open non-text files like audio files, image files, PDF or any other file containing special non-readable characters.

If we try to open a file that doesn’t exist, the interpreter will throw FileNotFound.

f = open("xyz.txt")
Output
FileNotFoundError: [Errno 2] No such file or directory: 'xyz.txt'

In the above example, if the xyz.txt file doesn’t exist in your system, then trying to open it throws FileNotFoundError

Python Closing a File


After opening a file, we read the content of the file or write something into it. After performing these file operations, it is important to close the opened file. After performing the required operations, the opened file should be closed to free the resources storing the file object. It means that if we don’t close the file, it will continue using the memory.

An opened file can be closed using the close() function.

f = open("example.txt")  # open the file
# do file operations
f.close()  # close the file

In the above example, the opened example.txt file is closed by writing f.close().

Closing using try...finally


Suppose while performing a read or write operation, some exception is thrown. In that case, the file would remain open and the resource storing the file object won’t be freed. 

We can prevent this by using the try...finally block. We can keep the code containing the opening of the file and the file operations inside the try clause and the file closing part inside the finally clause. We know that the finally clause is always executed, no matter if an exception is thrown or not. Thus, if an exception is thrown inside the try block, then the file will always get closed inside the finally clause.

try:
    f = open("example.txt")  # open the file
    # do file operations
 finally:
    f.close()  # close the file

If any exception is thrown inside the try clause in the above code, the f.close() statement inside the finally clause will get executed, thus closing the file.

Automatic Closing a File using with


Let’s again look at the following example.

f = open("example.txt")  # open the file
# do file operations
f.close()  # close the file

Here we are opening a file, performing some file operations and then closing it. The above code can be written using the with keyword as follows.

with open("example.txt") as f:
    # do file operations

In the above example involving the with keyword, the file gets automatically closed after the indented statements inside the with statement get executed, and so this is a good and preferred way to close files. Hence, we will be using this syntax in the rest of this chapter.

We now know how to open and close a file. So, let’s see how to perform the read and write file operations. 

Python Reading a File


To read the data stored in a file, it must be opened first in the read ‘r’ mode. After opening the file, the content of the file is read using the read() function.

Suppose you have a file named example.txt with the following content.

example.txt

Hello learners!
Welcome to the Python course of CodesDope.

Now if we want to print the content of this file, then we will have to first read the content and then print it.

with open("example.txt") as f:
    print(f.read())
Output
Hello learners!
Welcome to the Python course of CodesDope.

In this example, we opened the example.txt file and read its content using f.read() and printed this read content. The content returned by f.read() is of type string. Here we didn’t specify a mode while opening the file because read mode ‘r’ is the default mode.

Note that the string returned by f.read() is 'Hello learners!\nWelcome to the Python course of CodesDope.\n'. When it is printed using the print() function, ‘\n’ got printed as a new line and we got the output as shown in the above example.

In the beginning, the cursor (or pointer) is at the start of the content of the file. After reading the content of the file once, the position of the cursor reaches the end of the content. So, if we now try to read the content again, we will get an empty string.

with open("example.txt") as f:
    print("reading content 1st time")
    print(f.read())
    print("reading content 2nd time")
    print(f.read())
Output
reading content 1st time
Hello learners!

Welcome to the Python course of CodesDope.

reading content 2nd time

In the above example, when we read and printed the file content once, the cursor reached the end of the content. Now, there is no content after the current position of the cursor. Therefore, reading the file content for the second time returned and printed an empty string.

So, f.read() reads the whole content of the file at once. To read a specific number of characters from the current position of the cursor in the file, we need to pass the number of characters to be read as the argument to the read() function. For example, f.read(5) reads the first five characters from the current position of the cursor in the file.

Let’s see an example.

with open("example.txt") as f:
    print("reading content 1st time")
    print(f.read(8))
    print("reading content 2nd time")
    print(f.read(4))
    print("reading content 3rd time")
    print(f.read())
Output
reading content 1st time
Hello le
reading content 2nd time
arne
reading content 3rd time
rs!
Welcome to the Python course of CodesDope.

Initially, the cursor is placed at the start of the content of the file. Thus, f.read(8) reads the first 8 characters ‘Hello le’ of the content. So, now the current position of the cursor is after the 8th character in the content. After this, f.read(4) reads the next four characters ‘arne’ in the content shifting the position of cursor further by four characters. At last, f.read() reads the entire content after the cursor position.

Reading a File Line By Line


Suppose our example.txt file has the following content.

example.txt

Hello learners!
Welcome to the Python course of CodesDope.
Enjoy learning.

This file has three lines of text. Let’s see the different ways we can read the file content line by line.

We can use a for loop to read one line in each iteration of the loop. 

Look at the following example.

with open("example.txt") as f:
    for line in f:
        print(line)
Output
Hello learners!

Welcome to the Python course of CodesDope.

Enjoy learning.

You must have understood the code. We are iterating through the lines in file content and printing a line in each iteration. But why is there a blank line after every text line in the output?

This is because in the first iteration of the for loop, the value of the variable line is ‘Hello learners!\n’. So, when this string is printed, ‘\n’ gets printed as a new line. Therefore, a blank line got printed after each line. To prevent this, we can pass end = '' as an argument to the print function to replace new lines by a null string ‘’ on printing as shown below.

with open("example.txt") as f:
    for line in f:
        print(line, end = '')
Output
Hello learners!
Welcome to the Python course of CodesDope.
Enjoy learning.

We can see that no blank lines are getting printing now.

Another way to print individual lines of a file content is by using the readline() function. This function reads one line at a time. 

Let’s print the content of the example.txt file line by line.

with open("example.txt") as f:
    print("reading 1st line")
    print(f.readline())
    print("reading 2nd line")
    print(f.readline())
    print("reading 3rd line")
    print(f.readline())
Output
reading 1st line
Hello learners!

reading 2nd line
Welcome to the Python course of CodesDope.

reading 3rd line
Enjoy learning.

Initially, the cursor is placed at the start of the content of the file. The first f.readline() reads the first line of the content, bringing the cursor after the first line. Then the second f.readline() reads the second line, bringing the cursor after the second line, and the third f.readline() printed the third line.

Note that the string returned by the first f.readline() is ‘Hello learners!\n’. When printed, the ‘\n’ at the end got printed as a new line. Similarly, the other lines are also printed.

We can also read the lines of a file using the readlines() function. This function reads the lines from the current cursor position and returns a list containing the read lines as its elements.

Look at the following example.

with open("example.txt") as f:
    print(f.readlines())
Output
['Hello learners!\n', 'Welcome to the Python course of CodesDope.\n', 'Enjoy learning.']

Here, f.readline() read returns a list containing the three lines 'Hello learners!\n', 'Welcome to the Python course of CodesDope.\n' and 'Enjoy learning.' of the content as its elements.

Look at another example.

with open("example.txt") as f:
    print("reading content 1st time")
    print(f.read(10))
    print("reading content 2nd time")
    print(f.readlines())
Output
reading content 1st time
Hello lear
reading content 2nd time
['ners!\n', 'Welcome to the Python course of CodesDope.\n', 'Enjoy learning.']

The cursor is initially placed at the start of the file content. Thus, f.read(10) reads the first 10 characters ‘Hello lear’ of the content. This makes the current position of the cursor after the 10th character in the content. After this, f.readlines() reads the lines from the entire content after the current cursor position.

Now that we know the different ways we can read content of a file, let’s see how we can write something in a file.

Python Writing to a File


To write some data into a file, the file must be opened first in write ‘w’, append ‘a’ or exclusive creation ‘x’ mode. After opening the file, the data can be written into it using the write() function.

Again suppose you have a file named example.txt with the following content.

example.txt

Hello learners!
Welcome to the Python course of CodesDope.

Now, let’s write two sentences ‘This is a good course.’ and ‘Enjoy learning.’ into this file.

with open("example.txt", 'w') as f:
   f.write("This is a good course.\n")
   f.write("Enjoy learning.")
Output
23
15

In this example, we opened the example.txt file in the write mode. The first write() function writes the line "This is a good course." and the second function writes the line "Enjoy learning." into the file. We added a ‘\n’ at the end of the string passed to the first write() function to change the line after the string is written into the file.

The write() function returns the number of characters in the string passed to it and hence we got the output as 23 and 15. Let’s see what our example.txt file now looks like after running the above program.

example.txt

This is a good course.
Enjoy learning.

You can see that the data we added has overwritten the previous data of the file. This is because when a file is opened in the w mode, writing some data overwrites the previous data of the file.

Now, instead of overwriting the data, if we want to append some new data at the end of current data in a file, we need to open the file in the a mode.

Again assume our example.txt file has the following content.

example.txt

Hello learners!
Welcome to the Python course of CodesDope.

Let’s write two sentences ‘This is a good course.’ and ‘Enjoy learning.’ at the end of the current data in the file.

with open("example.txt", 'a') as f:
   f.write(" This is a good course.\n")
   f.write("Enjoy learning.")
Output
23
15

In this example, we opened the example.txt file in the append mode. Therefore, the strings added using the write() functions got appended to the content of the file. After running this program, the example.txt looks as shown below.

example.txt

Hello learners!
Welcome to the Python course of CodesDope. This is a good course.
Enjoy learning.

So, we now know how to read the data of a file and to write some data into a file. We also know that we open files in different modes if we want to read or write data to a file.

Now let’s see how to read or write something from somewhere in the middle of a file content.

Python tell() and seek()


When we read the content of a file, the interpreter starts reading from the first character of the content because initially the cursor is before the first character. However, there may be a case where we want to read the content from the 10th character. This can be possible if we were able to move our cursor after the 9th character of the content. We can perform such tasks using the tell() and seek() functions.

The tell() function returns the current position of the cursor.

with open("example.txt", 'r') as f:
    print("Cursor position before reading:", f.tell())
    f.read(10)
    print("Cursor position after reading:", f.tell())
Output
Cursor position before reading: 0
'Hello lear'
Cursor position after reading: 10

Before reading anything from the example.txt file, f.tell() returned the current position of the cursor as 0. Then we read the first 10 characters of the file, thus placing the cursor after the 10th character of the content. After reading the first 10 characters, f.tell() returned the current position of the cursor as 10.

Thus, we can know the position of the cursor after any operation using tell().

The seek() function moves the cursor to the specified position. It receives an integer as argument and places the cursor after the number of characters passed in the argument. For example, f.seek(10) places the cursor after the 10th character of the content of the file object stored in f.

Look at the following example to see how this function works.

with open("example.txt", 'r') as f:
    print("Cursor position before moving cursor:", f.tell())
    f.seek(10)
    print("Cursor position after moving cursor:", f.tell())
Output
Cursor position before moving cursor: 0
10
Cursor position after moving cursor: 10

The first f.tell() returned the position of the cursor as 0. f.seek(10) moved the cursor after the 10th character. After that, f.tell() returned the cursor position as 10. Note that the seek() function returns the value passed to it and hence seek(10) returned 10.

So this solves our problem, We can start reading from any position in the content.

In the following example, we are reading five characters after the 8th character of the file content.

with open("example.txt", 'r') as f:
    f.seek(8)
    print(f.read(5))
Output
8
arner

f.seek(8) moved the cursor after the 8th character in the file content. After that, f.read(5) read the next 5 characters from the current position of the cursor. Therefore, it read from the 9th character till the 13th character.

Similarly, we can write some text at any position in the file content.

Now you know how to do basic file operations in Python. You must also agree that file handling is easy in Python because we just need a few lines of code to read the content of a file or to write something in a file.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Doing the best at this moment puts you in the best place for the next moment.
- Oprah Winfrey


Ask Yours
Recent Posts
asds
asds
jasd
jasd
as
as
Post Yours
Doubt? Ask question