在 Python 讀取檔案內容十分簡單方便,以下會介紹用 Python 逐行讀取檔案內容的 4 種方法。
while
用 While 讀取檔案是最簡單的方法:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/python ## Open file fp = open('filename.txt', "r") line = fp.readline() ## 用 while 逐行讀取檔案內容,直至檔案結尾 while line: print line line = fp.readline() fp.close() |
with
|
1 2 3 4 |
#!/usr/bin/python with open(filename.txt,'r') as fp: all_lines = fp.readlines() |
readlines
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/python ## Open file fp = open('filename.txt', "r") # 變數 lines 會儲存 filename.txt 的內容 lines = fp.readlines() # close file fp.close() # print content for i in range(len(lines)): print lines[i] |
iter
|
1 2 3 4 5 6 |
#!/usr/bin/python fp = open('filename.txt', "r") for line in iter(fp): print line fp.close() |