在Python中,循環打印文件的操作可以通過以下技巧實現:
with
語句打開文件,并利用 for
循環逐行讀取和打印文件內容:with open('file.txt', 'r') as file:
for line in file:
print(line)
readlines()
方法一次性讀取文件的所有行,并利用 for
循環逐行打印:with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
readline()
方法逐行讀取文件內容,并在循環中打印:with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
read()
方法一次性讀取整個文件內容,并在循環中打印:with open('file.txt', 'r') as file:
content = file.read()
print(content)
這些技巧可以讓你靈活地操作文件內容,并通過循環打印文件的內容。