Python中文本文件讀取的方法有以下幾種:
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:
for line in file:
print(line)
with open('file.txt', 'r') as file:
lines = file.readlines()[:5] # 讀取前5行內(nèi)容
for line in lines:
print(line)
with open('file.txt', 'r') as file:
content = file.read()
words = content.split() # 分割成單詞列表
for word in words:
print(word)
這些方法可以根據(jù)具體的需求選擇使用,可以滿足大部分的文件讀取操作。