在Python中,讀取和處理TXT文件的常用方法有以下幾種:
file = open("example.txt", "r")
content = file.read()
file.close()
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
# 處理每一行的數(shù)據(jù)
print(line)
file = open("example.txt", "r")
line = file.readline() # 讀取第一行
while line:
# 處理每一行的數(shù)據(jù)
print(line)
line = file.readline() # 讀取下一行
file.close()
file = open("example.txt", "r")
for line in file:
# 處理每一行的數(shù)據(jù)
print(line)
file.close()
可以根據(jù)具體需求選擇適合的方法來讀取和處理TXT文件。