在Python中,您可以使用open()
函數來打開一個文本文件,并使用read()
方法來讀取文件的內容。以下是一個簡單的示例:
# 打開文件
file = open('example.txt', 'r')
# 讀取文件內容
content = file.read()
# 打印文件內容
print(content)
# 關閉文件
file.close()
在上面的示例中,open()
函數用于打開一個名為example.txt
的文本文件,并將其賦值給變量file
。然后,使用read()
方法來讀取文件的內容并將其保存在content
變量中。最后,打印文件的內容并使用close()
方法關閉文件。
另外,您也可以使用with
語句來自動關閉文件,避免忘記關閉文件的情況。示例如下:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
使用with
語句后,當代碼塊結束時,Python會自動關閉文件,而不需要顯式調用close()
方法。