2013/10/25

Python 讀取檔案內容

Python可以透過IO類別去讀取這三種類型檔案

  • Text I/O
  • Binary I/O
  • Raw I/O

我們先透過open方法將資料讀近來,open的方法有八種,在這邊我僅餵入檔案位址以及檔案權限

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open a disk file for updating (reading and writing)
'U'universal newlines mode (for backwards compatibility; should not be used in new code)

透過for each方式走訪檔案的內容,並印出來,strip()方法可以判斷是否走訪完全,也可以篩選一些文字

f = open('a.txt', 'r')

for line in f:
 print(line.strip())


參考資料:
http://docs.python.org/3/library/io.html
http://docs.python.org/3/library/functions.html#open
http://docs.python.org/3/library/stdtypes.html#str.split