python 的檔案處理

python 的檔案處理

python 要開啟檔案時,可呼叫內建的函式  open(filename, mode),mode有多種選擇:
'r' : 開啟檔案為讀取模式,此為預設模式。
'w':開啟檔案為可寫入模式,若檔案存在,則會被覆蓋內容。
'a':開啟檔案為可進行尾端附加寫入模式。
' b':檔案進行二進位資料處理


  • 檔案寫入模式
>>> f = open('workfile', 'w')
>>> f.write('This is the entire file.\n')
>>> print f
<open file 'workfile', mode 'w' at 0x020C4D88>
>>> f.close()

  • 檔案讀取模式
>>> myfile=open('workfile')
>>> myfile.readline()
'This is the entire file.\n'
>>> myfile.readline()
''


  • 檔案附加寫入模式
>>> f = open('workfile', 'a')
>>> f.write('Second line of the file\n')
>>> f.close()
>>> myfile=open('workfile')
>>> myfile.readline()
'This is the entire file.\n'
>>> myfile.readline()
'Second line of the file\n'
>>> myfile.readline()
''
>>> data=open('workfile').read()
>>> print data
This is the entire file.