python-day10--檔案處理

來源:互聯網
上載者:User

標籤:系統   管理   lex   break   swap   wap   檔案   coding   bre   

1.檔案:是作業系統提供的概念

2. open(r+‘檔案路徑‘ , ‘開啟檔案‘ , ‘用什麼字元編碼‘)   #r 表示原始字串

eg:open(r‘C:\Users\13264\Desktop\aaaa.py‘,‘r‘,encoding=‘utf-8‘)

3.檔案開啟:

     f=open(r‘aaaa.py‘)

  這個過程等於幹了兩件事:第一是作業系統開啟檔案,第二是在記憶體中開空間存一個變數

4.檔案回收:

    f.close    # 這是在關閉作業系統層級佔有的記憶體

5.檔案的處理方法:

     ①文字檔:唯讀模式,檔案不存在報錯  

     read    readable    readline    readlines   

     擴充:游標的移動seek

    ②文字檔:唯寫模式,檔案不存在會建立,檔案存在則會清空檔案內容

    write    writeable    writelines

    ③文字檔:只追加寫入模式,   ‘a‘     ,檔案不存在則建立,存在則在文本最後新增內容

    ④b模式:bytes模式

#rb
# f=open(‘aaaa.py‘,‘rb‘)
# print(f.read().decode(‘utf-8‘))

# f=open(‘1.jpg‘,‘rb‘)
# data=f.read()

#wb
# f=open(‘2.jpg‘,‘wb‘)
# f.write(data)


# f=open(‘new_3.txt‘,‘wb‘)
# f.write(‘aaaaa\n‘.encode(‘utf-8‘))

#ab
f=open(‘new_3.txt‘,‘ab‘)
f.write(‘aaaaa\n‘.encode(‘utf-8‘))

 

6.上下文管理:不用擔心檔案的close

# with open(r‘aaaa.py‘,‘r‘,encoding=‘utf-8‘) as read_f,\
# open(r‘aaaa_new.py‘,‘w‘,encoding=‘utf-8‘) as write_f:
# data=read_f.read()
# write_f.write(data)

  

7.#迴圈取檔案每一行內容

  with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) as f:
# while True:
# line=f.readline()
# if not line:break
# print(line,end=‘‘)

# lines=f.readlines() #只適用於小檔案
# print(lines)
for line in f: #推薦使用
         print(line,end=‘‘)



8.檔案的修改

#方式一:只適用於小檔案
# import os
# with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) as read_f,\
# open(‘a.txt.swap‘,‘w‘,encoding=‘utf-8‘) as write_f:
# data=read_f.read()
# write_f.write(data.replace(‘alex_SB‘,‘alex_BSB‘))
#
# os.remove(‘a.txt‘)
# os.rename(‘a.txt.swap‘,‘a.txt‘)


#方式二:
import os
with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) as read_f,\
open(‘a.txt.swap‘,‘w‘,encoding=‘utf-8‘) as write_f:
for line in read_f:
write_f.write(line.replace(‘alex_BSB‘,‘BB_alex_SB‘))

os.remove(‘a.txt‘)
os.rename(‘a.txt.swap‘,‘a.txt‘)
 

 

python-day10--檔案處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.