python基礎4

來源:互聯網
上載者:User

標籤:展現   換行   python基礎   with   python   with open   txt   多行   code   

開啟檔案方式:
f = open(‘db.txt‘,mode=‘r‘,encoding=‘utf-8‘) #開啟檔案,預設是唯讀,可以不加‘r’參數
fi=f.read() #可以不定義該變數,直接唯寫print(f.read()
print(fi)#讀所有,bytes---decode(‘utf-8‘)--->str
f.close() #回收作業系統的資源
#流程分析:
#1:向作業系統發起系統調用
#2:作業系統開啟這個檔案,返回一個檔案控制代碼給應用程式
#3: 在應用程式中把檔案控制代碼賦值給一個變數
#注意兩點:
#1:開啟一個檔案對應兩部分,一個Python層級的檔案控制代碼,另外一個是作業系統開啟的檔案(預設
#開啟檔案的編碼是以作業系統的編碼為準的,除非open()指定encoding=‘編碼‘ )
#2:當檔案操作完畢後,應該回收兩部分資源,
#del f:回收應用程式資源(python解譯器自動的記憶體回收機制已經替我們做了,所以可以省略)
#f.close:回收作業系統

with open(‘db.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
print(f.read())
f.close()
#with 確保不管使用過程中是否發生異常都會執行必要的“清理”操作,釋放資源,比如檔案使用後自動關閉、線程中鎖的自動擷取和釋放等。


f = open(‘db.txt‘,encoding=‘utf-8‘)
print(f.readlines()) #讀所有,並以列表的形式展現
f.close()

f = open(‘db.txt‘,encoding=‘utf-8‘)
print(f.readline()) #一次列印一行內容,多個readline則結果顯示多行內容
print(f.readline())
f.close()

往檔案寫的方式:
f = open(‘db.txt‘,mode=‘w‘,encoding=‘utf-8‘)
f.write(‘fffff\n‘) #如果檔案不存在則穿件,如果檔案存在則清空檔案再往裡寫內容
f.write(‘gggg\n‘) #寫多個write函數,則網檔案中添加多行內容,\n是分行符號號
f.write(‘hhhhh‘)
f.close()


l=[‘444\n‘,‘55555\n‘,‘66666\n‘]
f = open(‘db.txt‘,mode=‘w‘,encoding=‘utf-8‘)
for i in l: #通過for迴圈向檔案寫多行內容
f.write(i)
f.close()

l=[‘444\n‘,‘55555\n‘,‘66666\n‘]
f = open(‘db.txt‘,mode=‘w‘,encoding=‘utf-8‘)
f.writelines(l) #效果與上述for迴圈效果相同
f.close()

往檔案追加內容:
l=[‘444\n‘,‘55555\n‘,‘66666\n‘]
f = open(‘db.txt‘,mode=‘a‘,encoding=‘utf-8‘)
f.writelines(l)
f.close()
#a:追加寫入模式,如果檔案存在則把游標移動到檔案末尾,如果檔案不存在則建立

遍曆檔案所有所有內容:
f = open(‘db.txt‘,mode=‘r‘,encoding=‘utf-8‘)
for i in f:
print(i,end=‘‘)
f.close()

以bytes的形式去操作檔案內容,不能指定編碼:
with open(‘hezi.jpg‘,mode=‘rb‘) as f: #以二進位檔案方式開啟非字元檔案
print(f.read())

複製檔案練習
s = input(‘輸入源檔案:‘)
d = input(‘輸入目標檔案:‘)
with open(s,‘rb‘) as read_f,open(d,‘wb‘) as write_f:
for line in read_f:
write_f.write(line)
#以二進位的方法複製包括字元或者非字元檔案

python基礎4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.