逐行讀取檔案

逐行迭代檔案的最簡單方法:

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 行:世界