Home Backend Development Python Tutorial How to read txt file content in python

How to read txt file content in python

Jul 12, 2021 pm 03:49 PM
python read file

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.

How to read txt file content in python

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])
Copy after login

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
Copy after login
Copy after login

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()
Copy after login

The program execution result is:

Python教程
https://www.php.cn/course/list/30.html
Copy after login
Copy after login

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()
Copy after login

Program execution results For:

Python
Copy after login

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()
Copy after login

The program execution result is:

b'Python\xe6\x95\x99\xe7\xa8\x8b\r\nhttps://www.php.cn/course/list/30.html'
Copy after login

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])
Copy after login

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)
Copy after login

The execution result of the program is:

Python教程
Copy after login

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)
Copy after login

The running result is:

b'Python'
Copy after login

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()
Copy after login

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)
Copy after login

The running result is:

[b'Python\xbd\xcc\xb3\xcc\r\n', b'https://www.php.cn/course/list/30.html']
Copy after login

[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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles