Python學習 檔案操作

2021-10-14 07:29:41 字數 2010 閱讀 7998

開啟檔案通常使用open()函式開啟檔案。

open()函式返回的物件中,存在乙個叫close()的方法。關閉檔案通常使用close()。

模式:w(重頭寫),檔案不存在的情況下,會自動建立檔案。

try

:file

=open

("藏頭詩.txt"

,"w"

,encoding=

"gbk"

)#檔案位置,模式,檔案編碼

except filenotfounderror as e:

print

("出現了問題:"

+e.__repr__())

file

.writelines(

"我作飛鳥雲隨翼\n喜風伴柳輕入夢\n歡歌笑語十指扣\n你夢若記此生中"

)file

.close(

)

模式:a(追加內容)。

如果先寫的內容沒有完整,就需要追加內容。

try

:file

=open

("藏頭詩.txt"

,"w"

,encoding=

"gbk"

)#檔案位置,模式,檔案編碼

except filenotfounderror as e:

print

("出現了問題:"

+e.__repr__())

file

.writelines(

"我作飛鳥雲隨翼\n喜風伴柳輕入夢"

("藏頭詩.txt"

,"a"

,encoding=

"gbk"

)#檔案位置,模式,檔案編碼

except filenotfounderror as e:

print

("出現了問題:"

+e.__repr__())

file

.writelines(

"\n歡歌笑語十指扣\n你夢若記此生中"

模式:r(讀出)

try

:file

=open

("藏頭詩.txt"

,"r"

,encoding=

"gbk"

)#檔案位置,模式,檔案編碼

except filenotfounderror as e:

print

("出現了問題:"

+e.__repr__())

for i in

file

:print

(i,end="")

file

.close(

)

將藏頭詩.txt裡面的東西複製到藏頭詩1.txt

file1 =

open

("藏頭詩.txt"

,"r"

,encoding=

"gbk"

)file2 =

open

("藏頭詩1.txt"

,"w"

,encoding=

"gbk"

)file2.writelines(file1.readlines(

))

write適合寫入字元,字串 writelines適合寫入列表

要注意w,a,r這三種模式的用法。

Python學習 檔案操作

python使用open來開啟資料流 data open data.txt 下面是乙個讀取乙個檔案,然後逐行輸出的 try data open data.txt for each line in data try role,line spoken each line.split 1 print ro...

python學習 檔案操作

馮諾依曼體系架構 cpu由運算器和控制器組成 檔案io常用操作 開啟操作 open file,mode r buffering 1,encoding none,errors none,newline none,closefd true,opener none 開啟乙個檔案,返回乙個檔案物件 流物件 ...

Python學習 檔案操作IO

開啟檔案 以讀檔案模式開啟乙個檔案物件,使用open 函式,傳入檔名和標示符 file open e python.txt r 注意 路徑符號不能用 而是 讀檔案 f.read aaaa nbbb nbccc nddd neee nfff nhhh n 注意 read 會一次性讀取檔案的全部內容,如...