How do you read data from a txt file in Python?
In Python, you can use the open() function to open a txt file and the read() function to read the data inside. Here is a simple example:
# 打开txt文件
file = open("example.txt", "r")
# 读取文件中的数据
data = file.read()
# 输出数据
print(data)
# 关闭文件
file.close()
In the example above, example.txt is the file name of the txt file to be read. The first parameter of the open() function is the file name, and the second parameter is the mode in which the file is opened, where “r” stands for read mode. The read() function is used to read all the content in the file and store it in the variable data. Finally, the content of the variable data is printed using the print() function.