How to open a txt file using Python?

You can open a txt file using the built-in open() function in Python. Here is a simple example:

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

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

# 打印文件内容
print(content)

# 关闭文件
file.close()

In this example, ‘example.txt’ is the file name of the .txt file you want to open. The second argument ‘r’ indicates opening the file in read-only mode. Alternatively, you can use ‘w’ to open the file in write mode. Finally, remember to close the file after working with it to release resources.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds