在Python中,讀取文本內容的方法有以下幾種:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'r') as file:
for line in file:
print(line)
n = 5
with open('file.txt', 'r') as file:
for i in range(n):
line = file.readline()
print(line)
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
這些是常用的讀取文本內容的方法,根據具體需求選擇合適的方法進行操作。