search
HomeBackend DevelopmentPython TutorialHow to read txt file content in python

How to read txt file content in python

Jul 12, 2021 pm 03:49 PM
pythonread 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])

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!

Statement
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
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

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 Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools