How to open and read the content of a TXT file in Python?
To open and read the contents of a txt file, you can use the built-in open() function in Python to open the file and the read() method to read its contents. Here is an example code:
# 打开文件
file = open("filename.txt", "r") # "r"表示以只读方式打开文件
# 读取文件内容
content = file.read()
# 输出文件内容
print(content)
# 关闭文件
file.close()
In the code, “filename.txt” needs to be replaced with the actual path and file name of the text file to be opened. Additionally, use the close() method to close the file and release resources.
If you want to read the content of a file line by line, you can use the readlines() method, as shown below:
# 打开文件
file = open("filename.txt", "r")
# 逐行读取文件内容
lines = file.readlines()
# 输出文件内容
for line in lines:
print(line)
# 关闭文件
file.close()