How to Read a TXT File in Python

You can use the open() function in Python to read a txt file and print its contents. Here is an example code:

# 打开txt文件
with open('example.txt', 'r') as file:
    # 逐行读取文件内容并输出
    for line in file:
        print(line.strip())

In the example above, ‘example.txt’ is the file name of the txt file to be read, ‘r’ indicates opening the file in read-only mode. Then, a for loop is used to read the file content line by line, and the print() function is used to output the content of each line. Finally, the strip() function is used to remove the newline character at the end of each line.

bannerAds