逐行读取文件
逐行迭代文件的最简单方法:
with open('myfile.txt', 'r') as fp:
for line in fp:
print(line)
readline()
允许对逐行迭代进行更精细的控制。以下示例等同于上面的示例:
with open('myfile.txt', 'r') as fp:
while True:
cur_line = fp.readline()
# If the result is an empty string
if cur_line == '':
# We have reached the end of the file
break
print(cur_line)
一起使用 for 循环迭代器和 readline()
被认为是不好的做法。
更常见的是,readlines()
方法用于存储文件行的可迭代集合:
with open("myfile.txt", "r") as fp:
lines = fp.readlines()
for i in range(len(lines)):
print("Line " + str(i) + ": " + line)
这将打印以下内容:
第 0 行:你好
第 1 行:世界