Python之檔案操作

2021-08-08 11:24:43 字數 1252 閱讀 9652

使用open()「w」,以寫入模式開啟,如果檔案存在將會刪除裡面的所有內容,然後開啟這個檔案進行寫入

「a」,以追加模式開啟,寫入到檔案中的任何資料將自動新增到末尾

>>> fobj = open('/home/coder/documents/obama.txt')#唯讀開啟

>>> fobj

>>> fobj.close()#關閉檔案

>>> fobj = open('/home/coder/documents/obama.txt')

>>> fobj.read()#一次讀完整個檔案

>>> fobj.readline() #每次讀一行,但之前已經讀到檔案末尾,返回空

''>>> fobj.close()

>>> fobj = open('/home/coder/documents/obama.txt')

>>> fobj.readline()

'hello, everybody! \n'

>>> fobj.close()

>>> fobj = open('/home/coder/documents/obama.txt')

>>> fobj.readlines() #讀取所有行到列表中

>>> fobj.close()

>>> fobj = open('/home/coder/documents/obama.txt','w')#寫入模式開啟檔案

>>> fobj.write('one more line')#往檔案中寫內容

13>>> fobj.close()

>>> fobj = open('/home/coder/documents/obama.txt')

>>> s = fobj.read()

>>> s

'one more line'

>>> fobj.close()

>>>

我們也可以使用with語句處理檔案物件,它 try-finally塊的簡寫,它會在檔案用完之後自動關閉檔案,即使發生異常也沒關係。

>>> 

with open('/home/coder/documents/obama.txt') as fobj:

...

for line in fobj:

... print(line, end = ' ')

...

one more line

>>>

Python之檔案操作

file open filename,mode mode預設為 r 例如file ope test.txt r 以讀的方式開啟檔案.檔案操作完畢記得關閉.file.close 其中,mode可以有以下選擇 檔案test.txt的內容為 11111111111 aaaaaaaaa 2222222222...

Python之檔案操作

建立目錄import os import errno defmkdir dir try os.makedirs dir except oserror as exc if exc.errno errno.eexist print the dir has been existed pass else r...

Python之 檔案操作

1 開啟檔案 f open hello.txt a 開啟 hello.txt 檔案 r 唯讀模式,開啟的檔案不存在的話,會報錯 w 只寫模式,會清空原來檔案的內容 a 追加模式 開啟的檔案不存在,會新建乙個檔案2 讀寫檔案 f open hello.txt a f.write joly,123 np...