1. 程式人生 > >python基礎語法 - 文件操作

python基礎語法 - 文件操作

opened odi 函數 文件 pre 通過 語法 pytho isp

對文件操作流程

  1. 打開文件,得到文件句柄並賦值給一個變量
  2. 通過句柄對文件進行操作
  3. 關閉文件

現有文件如下:

技術分享圖片
昨夜寒蛩不住鳴。
驚回千裏夢,已三更。
起來獨自繞階行。
人悄悄,簾外月朧明。
白首為功名,舊山松竹老,阻歸程。
欲將心事付瑤琴。
知音少,弦斷有誰聽。
xiaochongshan

1.open()方法:

  file 對象使用 open 函數來創建

f = open(xiaochongshan,r,encoding=utf-8)  #打開文件
f.read()    #讀取文件
f.close()   #關閉文件

with方法:

  1.with方法可以省去f.close,當退出with語句時,默認f.close(推薦)

with open(log,r) as f:
    f.read()
    f.readline()

  2.同時管理多個文件對象時

with open(log,r) as f_read,open(log2,w) as f_write:
    for line in f_read:
        f_write.write(line)

python基礎語法 - 文件操作