Python 讀取檔案內容有不同方法, 以下會介紹 Python 3 種讀取檔案內容的方法。
但在開始前先了解一下開啟檔案的模式, 這個跟其他程式語言相似, 每種模式也有不同, 它們分別是:
r – read only
w – write only
a – append only
r+ – read as well as write
w+ – write as well as read
a+ – append as well as read
由上面可以看出, 如果要讀取檔案內容, 開啟的模式需要設定成 r, r+, w+ 或 a+, 知道要設定的模式後, 現在是開啟及讀取檔案的部份了。
Python read()
read() 函式在 Python 已經內建, 語法是:
file_object.read( n )
file_open_object 是用 open() 函式建立的物件, 而 “n” 是要讀取的位元組, 如果要整個檔案合部讀取, 省略便可以, 例如:
1 2 3 4 |
#!/usr/bin/python file = open("filename.txt", "r") print(file.read()) |
以上程式碼會開啟 filename.txt 檔案, 並把全部內容印出。
Python readline()
readline() 是另一個 Python 內建的函式, 用法跟 read() 差不多, 主要分別是每次執行只會讀取一行內容, 比較適合讀取大檔案。
例如檔案內容是這樣:
PHP
C
C++
Java
用 readline() 開啟以上檔案:
1 2 3 4 |
#!/usr/bin/python file = open("filename.txt", "r") print(file.readline()) |
由於以上只執行一次, 所以只會印出第一行, 即 “Python\n”, 這裡要注意, readline() 會連同換行字元 “\n” 一同印出。
那麼如果要將檔案全部內容輸出, 可以配合 for 或 while 來做, 以下是用 for 的寫法:
1 2 3 4 5 6 |
#!/usr/bin/python file = open("filename.txt", "r") for line in file.readlines(): line = line.strip() ### 刪除每行頭尾空白字符 print line ### 印出內容 |
Python readlines()
readlines() 會將整個檔案讀取, 並把每一行回傳到 list 內, 每行一個內容, 寫法:
1 2 3 4 |
#!/usr/bin/python file = open("filename.txt", "r") print(file.readlines()) |
以上會印出以下內容:
1 |
['Python\n', 'PHP\n', 'C\n', 'C++\n', 'Java\n'] |