Python中讀取txt文件的方法有多種。以下是常見的幾種方法:
file = open("file.txt", "r")
content = file.read()
file.close()
with open("file.txt", "r") as file:
content = file.read()
with open("file.txt", "r") as file:
lines = file.readlines()
with open("file.txt", "r") as file:
for line in file:
# 處理每一行的內容
無論選擇哪種方法,都需要確保文件存在且可讀。另外,還需要注意文件路徑的正確性和編碼方式的匹配。