示例代码如下:
withopen('example.txt', 'r') as f:
while True:
line = f.readline()
if not line:
break
print(line)
这段代码使用了with open
语句打开了一个文件example.txt
,并用f
变量引用它。在循环中使用f.readline()
来读取文件的每一行,并在每次循环中打印这一行.如果读取的内容为空,即到达文件末尾,则退出循环.