python中檔案讀寫 open函式詳解

2021-10-18 19:38:02 字數 3212 閱讀 3574

在python中檔案的讀取分為三步走:

讀:開啟檔案 -> 讀檔案 -> 關閉檔案

(有點像把大象放進冰箱需要幾步?的問題)

open函式主要運用到兩個引數,檔名和mode,檔名是新增該檔案物件的變數,mode是告訴編譯器和開發者檔案通過怎樣的方式進行使用。因此在python中開啟檔案的**如下:

file_object =

open

('filename'

,'mode','encoding'

)

mode

mode引數可以不寫,預設mode引數是「r」。mode引數如下:

file

=open

('testfile.txt'

,'w'

)file

.write(

'hello world\n'

)file

.write(

'this is our new text file\n'

)file

.write(

'and this is another line. \n'

)file

.write(

'why? because we can. \n'

)file

.close(

)

執行**以後,在本地就會出現乙個叫test file的文字檔案,裡面的內容為:

hello world

this is our new text file

and this is another line

why? because we can.

file

=open

('testfile.text'

,'r'

)print

(file

.read(

))

將會把該文字檔案中所有的內容展示出來

另外,如下只想列印檔案檔案中的部分內容,也可以採用下面的方式

file

=open

('testfile.txt'

,'r'

)print

(file

.read(5)

)

編譯器將會讀寫文字檔案中儲存的前5個字元

如果想要逐行輸出,而不是把所有內容列印出來,以至於沒有換行、所有內容都擠在一起,那麼需要呼叫readlines()函式。當呼叫這個方法的時候,將會把文字中的每一行作為乙個元素放在list中,返回包含了所有行的list。

file

=open

('testfile.txt'

,'r'

)print

(file

.readlines(

))

如果需要指定列印出第二行,**如下:

file

=open

('testfile.txt'

,'r'

)print

(file

.readlines()[

1])

我們也可以採用迴圈的方式的將檔案中的內容逐行輸出:

file

=open

('testfile.txt'

,'r'

)for line in

file

:print

(line)

檔案寫入也是三步:開啟檔案——寫入檔案——關閉檔案

file

=open

('testfile.txt'

,'w'

)file

.write(

'this is a test'

)file

.write(

'to add more lines.'

)file

.close(

)

當操作完成之後,使用file.close()來結束操作,從而終結使用中的資源,從而能夠釋放記憶體。

為了避免開啟檔案後忘記關閉,占用資源或當不能確定關閉檔案的恰當時機的時候,我們可以用到關鍵字with,舉例如下:

# 普通寫法

file1 =

open

('abc.txt'

,'a'

) file1.write(

'張無忌'

) file1.close(

)# 使用with關鍵字的寫法

with

open

('abc.txt'

,'a'

)as file1:

#with open('檔案位址','讀寫模式') as 變數名:

#格式:冒號不能丟

file1.write(

'張無忌'

)#格式:對檔案的操作要縮排

#格式:無需用close()關閉

fh =

open

('hello.txt'

,'r'

)

fh =

open

('hello.txt'

,'r'

)print

(fh.read(

))

3、將新的資訊寫入文字中、並擦除原來的資訊:

fh =

open

('hello.txt'

,'w'

)

fh.write(

'put the text you want to add here'

) fh.write(

'and more lines if need be.'

)

fh.close(

)

4、在現存的檔案中加入新的內容、不會擦除原來的內容:

fh =

open

('hello.txt'

,'a'

) fh.write(

'we meet again world'

) fh.close(

)

python 讀寫檔案 open

io 檔案讀寫 讀 f open users panbingqing desktop test a.rtf 讀模式,不可做任何修改 將整個檔案內容讀取為乙個字串值,使用read 方法 f1 f.read or use readlines 將整個檔案讀取為列表 f2 f.readlines type ...

Python中open讀寫檔案操作

python內建了讀寫檔案的函式open f open users michael test.txt r r 表示讀,我可以可以利用這個方法開啟乙個檔案,如果檔案不存在,會丟擲乙個ioerror的錯誤,並且給出錯誤碼和詳細資訊告訴你檔案不存在。如果檔案開啟成功,我們接下來就要讀檔案操作了 f.rea...

Python中檔案操作open 函式

1.讀取檔案內容 f open r 檔案存在的路徑 檔名稱.檔案字尾名 r 路徑前面的r的作用是防止反斜槓被轉義 用read 方法讀取檔案 r 模式唯讀檔案 f open r d desktop test.txt r encoding utf 8 errors ignore a f.read pri...