Read Text File in Python: Quick Guide

In Python, you can use the open() function to read the contents of a txt file.

The sample code is as follows:

# 打开txt文件
file = open("example.txt", "r")

# 读取文件内容
content = file.read()

# 输出文件内容
print(content)

# 关闭文件
file.close()

The open() function takes two parameters, with the first parameter being the file name to open and the second parameter being the mode in which to open the file. The mode “r” indicates read-only mode, meaning that the file content can only be read.

The read() method can be used to read the contents of a file, which will return the entire file’s content as a string.

Finally, remember to call the close() method to close the file after reading its contents.

bannerAds