How to read txt files in python: 1. Use the read() function to read the contents of the txt file byte by byte or character; 2. Use the readline() function to read the contents of the txt file line by line. ;3. Use the readlines() function to read multiple lines of content in the txt file at one time.
The operating environment of this tutorial: windows7 system, python3.7 version, DELL G3 computer
Python provides the following 3 functions, they are It can help us realize the operation of reading data in the file:
read() function: read the contents of the file byte or character by byte;
-
readline() function: read the contents of the file line by line;
readlines() function: read the contents of multiple lines of the file at once.
Python read() function
For the open() function, and in readable mode (including r , r, rb, rb), you can call the read() function to read the contents of the file byte by byte (or character by character).
If the file is opened in text mode (non-binary mode), the read() function will read character by character; conversely, if the file is opened in binary mode, the read() function will read byte by byte to read.
The basic syntax format of the read() function is as follows:
file.read([size])
Among them, file represents the opened file object; size is an optional parameter used to specify the maximum number of characters that can be read at one time (bytes) number, if omitted, the default is to read everything at once.
For example, first create a text file named my_file.txt, whose content is:
Python教程 https://www.php.cn/course/list/30.html
Then create a file.py file in the same directory as my_file.txt, And write the following statement:
#以 utf-8 的编码格式打开指定文件 f = open("my_file.txt",encoding = "utf-8") #输出读取到的数据 print(f.read()) #关闭文件 f.close()
The program execution result is:
Python教程 https://www.php.cn/course/list/30.html
Note that when the file operation is completed, the close() function must be called to manually close the open file, so that It can avoid unnecessary errors in the program.
Of course, we can also specify the maximum number of characters (or bytes) that read() can read each time by using the size parameter, for example:
#以 utf-8 的编码格式打开指定文件 f = open("my_file.txt",encoding = "utf-8") #输出读取到的数据 print(f.read(6)) #关闭文件 f.close()
Program execution results For:
Python
Obviously, the read() function in this program only reads the first 6 characters of the my_file file.
Again, size represents the maximum number of characters (or bytes) that can be read at one time. Therefore, even if the set size is greater than the number of characters (bytes) stored in the file, the read() function will not No error will be reported, it will only read all the data in the file.
In addition, for files opened in binary format, the read() function will read the contents of the file byte by byte. For example:
#以二进制形式打开指定文件 f = open("my_file.txt",'rb+') #输出读取到的数据 print(f.read()) #关闭文件 f.close()
The program execution result is:
b'Python\xe6\x95\x99\xe7\xa8\x8b\r\nhttps://www.php.cn/course/list/30.html'
You can see that the output data is a bytes byte string. We can call the decode() method to convert it into a string we recognize.
Python readline() function
readline() function is used to read a line in the file, including the final newline character "\n ". The basic syntax format of this function is:
file.readline([size])
where file is the open file object; size is an optional parameter, used to specify the maximum number of characters (bytes) read at one time when reading each line. .
Same as the read() function, the prerequisite for this function to successfully read file data is that the mode specified by the open() function to open the file must be readable mode (including r, rb, r, rb) ).
The following program demonstrates the specific usage of the readline() function:
f = open("my_file.txt") #读取一行数据 byt = f.readline() print(byt)
The execution result of the program is:
Python教程
Because the readline() function reads the content of a line in the file , the last newline character "\n" will be read, and the print() function will wrap the content by default when outputting the content, so you will see an extra blank line in the output result.
Not only that, when reading line by line, you can also limit the maximum number of characters (bytes) that can be read, for example:
#以二进制形式打开指定文件 f = open("my_file.txt",'rb') byt = f.readline(6) print(byt)
The running result is:
b'Python'
Compared with the output of the previous example, since one line of data is not completely read here, the newline character will not be read.
Python readlines() function
readlines() function is used to read all lines in the file. It and the call do not specify the size parameter. The read() function is similar, except that the function returns a list of strings, where each element is a line of content in the file.
Like the readline() function, the readlines() function reads each line along with the newline character at the end of the line.
The basic syntax format of the readlines() function is as follows:
file.readlines()
Among them, file is the open file object. Like the read() and readline() functions, it requires that the mode of opening the file must be readable mode (including r, rb, r, rb).
For example:
f = open("my_file.txt",'rb') byt = f.readlines() print(byt)
The running result is:
[b'Python\xbd\xcc\xb3\xcc\r\n', b'https://www.php.cn/course/list/30.html']
[Related recommendations: Python3 video tutorial]
The above is the detailed content of How to read txt file content in python. For more information, please follow other related articles on the PHP Chinese website!

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!