How to read txt file content in python
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

The MySQL connection may be due to the following reasons: MySQL service is not started, the firewall intercepts the connection, the port number is incorrect, the user name or password is incorrect, the listening address in my.cnf is improperly configured, etc. The troubleshooting steps include: 1. Check whether the MySQL service is running; 2. Adjust the firewall settings to allow MySQL to listen to port 3306; 3. Confirm that the port number is consistent with the actual port number; 4. Check whether the user name and password are correct; 5. Make sure the bind-address settings in my.cnf are correct.

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.
