How to read and write files with Python

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.

Use open() to read files

In 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 parameter

There 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.

A simple example

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).

Create text file and write content

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')

read() example

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)

Write file content

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:

Use the with statement

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()

Word Segmentation and Statistics

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

How to read and write files with Python
How to delete files and directories in python
Python open read and write
Python file read and write operations
How to write python configuration file
How to write classes in python
How to read Excel in Python
How to write return in python
How to make a globe with Python
How to use and and or in Python
How to delete cache files in python
How to save text files in python
How to write try statement in python
How to process excel table with python
How to get started quickly with Python
How to convert web pages to PDF with Python
How to play happily with Python3 on Ubuntu
Teach you how to write games in python
Python how to delete rows with empty columns
Python memory mapped file read and write method
How to write a confession program in python
How to deal with python file reading failure
How does Python store data to json files
How to repackage Deb files under Debian and Ubuntu
How to comment python code
How to write Pythonic code
How to learn python quickly
How to uninstall python plugin
3 ways to encrypt Python files
How to understand python objects
How to use python tuples
python how to view webpage code
How to use python thread pool
python ftp upload files and folders
Use C++ to write Python3 extensions
How to wrap in python code
How to save the python program
How to omit parentheses in Python
How to install Python 3.8 on CentOS 8
How to install Python 3.8 on Ubuntu 18.04
How to filter numbers in python
Centos6.7 comes with python upgrade to
How to install Python on CentOS 8
How to solve python dict garbled
How to view errors in python
Played with stocks and learned Python
How does Python generate xml files
Python reads and writes json files
How to view the python module
How to understand variables in Python
How to clear variables in python
How to understand python object-oriented programming
How to use SQLite in Python
ubuntu configuration python, Red
Python3 configuration and entry.md
How to write python configuration file
How to introduce third-party modules in Python
How to represent null values in python
Python tricks and tricks-continue to be updated...
How to use PYTHON to crawl news articles
Getting started with python-2: functions and dictionaries
How to run id function in python
How to install third-party modules in Python