1. 程式人生 > >python讀取檔案並處理成行

python讀取檔案並處理成行

python讀取檔案比Java簡潔很多:

def read_line(file):
    """
    text to lines    cool
    :param file: file name
    :return: the content of text line by line
    """
    with open(file) as f:
        for line in f:
            yield line.strip()


lines = read_line("text")

print(type(lines))


print(next(lines))
print('-----------------------------------------------------------------')
# 剛好輸出了一個完整的檔案,而且一個都不多一個都不少,恰好包含上面next輸出的元素,生成器果然能維持指標的位置
for line in lines:
    print(line)

以上程式碼用到生成器知識,可以減少記憶體的使用,如果檔案非常大的話就不用將讀取的每一行新增到一個list等容器中