leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Opening, reading and writing of Python files

Estimated reading: 8 minutes 55 views

Variables are a good way to save data while the program is running, but if we still want to save data after the program ends, we need to save the data to a file.

Everyone should be familiar with files, which can store many different types of information on a computer. A file can contain text, pictures, sounds, images, and computer programs.

The file has the following 3 key attributes.

  • File name: To distinguish between different files, give each file a unique name.
  • File Type: Indicates what type of content is contained in the file. The file name usually contains a period, and the part after the period is called the “extension”, which can indicate the type of the file. For example, a.txt represents a text file, b.mp3 represents a sound file, c.mp4 represents a video file, and d.py represents a Python computer program file.
  • Path: The location on the computer where the file is stored. For example, D:\Python Programs is a path. The D:\ part is the root directory, which is also called the D drive in Windows. And Python Programs is a folder. Folders can also have other folders, and folders inside other folders are called subfolders.

Next, we focus on how to use Python to manipulate text files.

Python open file

The ability to read and write files on disk is provided by the operating system. To read and write a file is to request the operating system to open a file object, and then read data from the file object through the interface provided by the operating system, or write data to the file object. The general steps for manipulating files in Python are: open the file, read or write to the file, close the file. Let’s first look at how to open a file.

We first create a text file called “Ancient Poems 1” in the Python Programs folder of the D drive. In this file, we enter the famous poem written by Li Bai – “Silent Night Thoughts”, as shown in Figure 1. .

Python open file
figure 1
When opening a file, a file object is created in Python. Create a file object using the open() function. The open() function can accept two parameters, the first parameter is the path of the file, and the second parameter is the mode to open the file. The sample code to open the text file “Ancient Poem 1” is shown below.

txtFile=open(“D:\Python Programs\Ancient Poems 1.txt”,”r”)
There are three types of file opening modes that are often used:

  • r: means read-only, it is also the default mode;
  • w: means writing, the new content will overwrite the original content;
  • a: means appending to the end of the file without overwriting the original content.

Next, we will describe the usage of each open mode in detail.After using the open() function to open the file and create the object txtFile, we can use this file object to do other work.

Python read file

When we have a file object, we can perform various operations on the file. If you just read the contents of the file, when calling the open() function, the second parameter passed is the letter “r”, which means read. The file can then be read using another function, readlines().

Let’s look at an example, or open the text file “Ancient Poetry 1.txt”, then read the content inside, and print it to the screen, the code is as follows.

txtFile=open("D:\Python Programs\Ancient Poems 1.txt","r")

We call the readlines() function of the file object txtFile and assign the returned content to the variable lines, and then print the lines to the screen.

It is also important to note that when the file is processed, be sure to call the close() function to close the file. If the file is not closed, an exception may occur when another program tries to use the same file. So it is better to have a close() function for each open() function.

Run the code and get the result shown in Figure 2.

Python read file
figure 2
We read lines of text from the file “Ancient Poems 1.txt”, and then assign them to the list of lines. Each item in the list is a string that contains each line in the file. In addition, since we pressed the Enter key after each line of text when entering the file, there will be a \n at the end of each line, indicating a newline.

In addition to using lines to read the text in the file at one time, we can also call the readline() function to read the text line by line. Take reading “Ancient Poem 1.txt” as an example, this time use the readline() function to read the text. We use the while loop to read all the text in the file, and add a judgment condition. When the read content is empty, it means that all the content has been read, and we will jump out of the while loop. code show as below.

txtFile=open("D:\Python Programs\Ancient Poems 1.txt","r")
while True:
    if not line:

Or open the file through the open() function, and create the object txtFile. Then use a while loop with a condition of True, which means that the loop will continue to run until a specific condition is met, and the break statement in the loop can be executed to break out of the loop.

In the loop, call the readline() function to read a line of text and assign it to the variable line. Then judge whether the line is empty. If it is empty, it means that the end of the file is reached, and the loop is jumped out; if it is not empty, it means that the content is read, and the string in the line is output to the screen. After the while loop ends, call the close() function to close the file.

Let’s run the code and get the result shown in Figure 3.

image 3

Python writes to file

In the previous section, we introduced the method of reading a file, and then we will introduce how to write text to the file. The open() function is also used to write text. The first parameter is also the path of the file, and the second parameter is changed to “w”, which means write (write). Then you can use the write() function to write to the file.

To see an example, open the text file “Ancient Poems 1.txt” that we created in the previous section, and save it as “Ancient Poems 2.txt” (note that the poem “Quiet Night Thoughts” is in the file at this time ), and then write the content to the file “Ancient Poetry 2.txt”. code show as below

txtFile=open("D:\Python Programs\Ancient Poems 2.txt","w")
txtFile.write("Tang Meng Haoran\n")
txtFile.write("Chun Mian does not wake up\n")
txtFile.write("Listen to birds everywhere\n")
txtFile.write("The sound of wind and rain at night\n")
txtFile.write("How much does the flower fall\n")

Here, the write() function of the file object txtFile is called, and the string to be written is passed in as a parameter. We will add a \n at the end of the string to indicate a newline. When you are done writing what you want to write, call the close() function to close the file.

Run the code, open the “Ancient Poetry 2.txt” text file, and see the content shown in Figure 4.

Python writes to file
Figure 4
We will see that the content of “Quiet Night Thoughts” in the file “Ancient Poems 2.txt” has disappeared, replaced by the poem “Spring Dawn”. But sometimes, we may not want to replace the original content, just want to add some content. At this time, “w” is not used to open the mode, but “a” is used instead, which means append.

This time we want to add the missing “Silent Night Thoughts” to the bottom of the poem “Chun Xiao”. code show as below.

txtFile=open("D:\Python Programs\Ancient Poems 2.txt","a")
txtFile.write("Silent Night Thoughts\n")
txtFile.write("Tang Li Bai\n")
txtFile.write("Moonlight in front of the bed\n")
txtFile.write("Suspected of frost on the ground\n")
txtFile.write("Look up at the bright moon\n")
txtFile.write("Looking down and thinking about my hometown\n")

Let’s run the code and open the “Ancient Poetry 2.txt” text file again, and see the content shown in Figure 5.

Python writes to file
Figure 5
We will see that under “Spring Dawn”, the poem “Silent Night Thoughts” has been added.

Tip: Sometimes, the file we want to open does not exist. In this case, if the file is opened in read-only mode, Python will report an error, and if it is opened in write or append mode, Python will create a new file for us to write to.

Leave a Comment