Book recommendation: "Python University Practical Course"
Best for beginners
In this article, we will learn how to read a file with Python, then write content to the file and save it again. Using Python to read and write a particular type of file, such as JSON, CSV, Excel, etc., usually has a dedicated module. However, here, we will open a text file (.txt) in Python.
If you use Python's open
function, it will return a file object, which will contain some methods and attributes. We can use these methods and properties to obtain information about the opened file, and we can use these methods to change the opened file.
open()
to read filesIn this section, we will learn how to use the open()
function to load files in Python. The simplest example is to open a file and create a file object.
When opening a file with Python's open()
function, several parameters are available. However, the most commonly used parameters are only the first two. Note that the first one is mandatory, and the rest are optional. If you don't add the mode
parameter, the file will be opened in read-only mode in Python.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
mode
parameterThere are different modes for reading files. As mentioned earlier, if the mode
parameter is not included, the file will be opened as read-only. As shown below, several commonly used open modes are listed.
Among them, mode='r'
means read-only; mode='w'
means write only; mode='a'
means append. mode='r+'
means readable and writable, but the file must exist, otherwise an error will be reported.
In the following code example, use open()
to open a file. It is assumed that the file and the Python script are in the same directory, otherwise the path must be added.
exfile =open('example_file')print(exfile)
In the above figure, it is obvious that we have a file object opened in read-only mode, and there are no other parameters in open()
except the file name. Therefore, nothing can be written to the file. If you want to print the file name, just type print(exfile.name)
.
Now use open()
to create a new file. Now, use the mode='w'
parameter so that a file object can be opened and the "file object write" method can be used.
exfile =open('example_file2','w')print(exfile)
In the above figure, the current file object can be in write mode ('w'). In the following code block, we will add a line of text to this file:
exfile.write('This is example file 2 \n')
Of course, you can also add more lines:
exfile.write('Line number 2, in example file 2')
exfile.close()
Note that you must use close()
to close the file in the last line. In the image below, we can see a sample file created in Python.
How to use open() to read a text file in Python
In the next example of reading a file with Python, we will learn how to open a text file (.txt) in Python. Of course, this is very simple, we have basically mastered how to use Python to achieve this purpose. In other words, if we only want to read .txt files in Python, we can use the open function and read mode:
txtfile =open('example_file.txt')
This operation is very simple. Now, if we want to print the contents of a text file, there are three ways. The first one is to use the read()
method of the file object to read the entire file content. In other words, using txtfile.read()
can get the following output:
The second is to use readlines()
to read the file into the list:
txtfile =open('example_file.txt')print(txtfile.readlines())
In this method, you can also use to provide parameters to read certain rows. For example, the following code will read the first two lines in and print them out:
txtfile =open('example_file.txt')
line = txtfile.readlines(1)print(line)
line2 = txtfile.readlines(2)print(line2)
The last method is to print the contents of the file line by line through a loop:
txtfile =open('example_file.txt')for line in txtfile:print(line)
In the example, open a .txt
file and add content to it by appending, so it needs to be opened in 'a'
mode.
open('example_file2.txt','a')
Next, use write()
to append content to it.
txtfile.write('\n More text here.')
When adding text, at least in Windows 10, you must add \n
before the line. Otherwise, a new line will be added after the last character (on the last line of the file). If we want to add more rows, we must also remember to do this;
txtfile.write(‘\nLast line of text, I promise.)
txtfile.close()
You can open the text file with a text editor (for example, Notepad, Gedit), and you will see the last two lines added:
Using the with statement to open a file is a very good habit, so that you don't have to remember to close the file, and the syntax of using the with statement is clear and easy to read:
withopen('example_file2.txt')as txtfile2:print(txtfile2.read())
Now, if we use the read()
method, Python will throw a ValueError:
txtfile2.read()
After reading the file, you can use the split()
method of the string to split the sentence in the text file into words, and then use the Counter
class in the collections module to count the number of words in the opened file.
from collections import Counter
withopen('example_file2.txt')as txtfile2:
wordcount =Counter(txtfile2.read().split())print(len(wordcount))
# Output:43
Now, the Counter
class returns a dictionary containing all words and the number of occurrences of each word. Therefore, you can print all words and the total number of words like this:
for k insorted(wordcount, key=wordcount.get, reverse=True):print(k, wordcount[k])
In the code example above, we loop through the keys in the dictionary and sort them. In this way, the most common words are ranked at the top. Of course, if you use Python to read a file containing multiple words and print the result like this, this operation is not feasible.
The above describes the methods of reading files in different modes, creating and writing files, appending data to files, and how to use the with statement to read files.
Recommended Posts