重學Python,學python

來源:互聯網
上載者:User

重學Python,學python
檔案的讀操作

 

樣本:

 1 print("->檔案控制代碼的擷取,讀操作:") 2  3 f = open('無題','r',encoding='utf8') 4 d = f.read() 5 f.close() 6 print(d) 7  8 print('->例二:') 9 f = open('無題','r',encoding='utf8')10 e = f.read(9)11 f.close()12 print(e)13 #python3中,檔案中一個中英文都佔位1

運行結果:

->檔案控制代碼的擷取,讀操作:昨夜星辰昨夜風畫樓西畔桂堂東身無彩鳳雙飛翼心有靈犀一點通->例二:昨夜星辰昨夜風畫

 

檔案的寫操作

 

知識點:

    1. 寫操作前,檔案先格式化清空檔案

    2.清空操作,在執行open的w方法後,清空

1 print("寫的操作,寫檔案的時候,不能調用讀方法,讀檔案的時候,不能調用寫方法")2 3 f = open('python','w',encoding='utf8')4 f.write("I must learn python \nbecause, python is important \n")5 f.write("java is better?")6 f.write("maybe") #上面的語句,沒有加分行符號,所以輸出的內容是緊接的7 f.close()

運行結果:

開啟檔案後顯示如下

I must learn python because, python is important java is better?maybe

 

檔案的append方法

 

文法格式:

f = open('檔案名稱','a','encoding = utf8')

檔案這種方法為追加模式:1, 空白檔案中,直接從頭開始寫入內容; 2 有內容的檔案,會在末尾開始繼續寫入內容

樣本:

f = open('python','a',encoding='utf8')f.write("花開又花落")f.close()

運行結果:

I must learn python because, python is important java is better?maybe花開又花落

 

readline 和 readlines

 readline是逐行讀取

readlines是全文讀取

樣本:

 1 print("readline方法") 2 f = open('無題','r',encoding='utf8') 3 a = f.readline() 4 print("此時游標位置:",f.tell()) 5 b = f.readline() 6 print("此時游標位置:",f.tell()) 7 print(a.strip())  #strip是字串方法中去除空格和換行的方法 8 print(b.strip()) 9 10 11 print("readlines方法,會將每行的內容組成一個列表列印")12 f = open('無題','r',encoding='utf8')13 c = f.readlines()14 print(c)15 print(id(c))16 print(id(f))17 for i in c:18     print(i.strip())19 print("遍曆方法")20 f.seek(0)21 for i in f:22     print(i.strip())23 f.close()  #檔案的操作中,close()方法一定不能忘記

運行結果:

readline方法此時游標位置: 23此時游標位置: 46昨夜星辰昨夜風畫樓西畔桂堂東readlines方法,會將每行的內容組成一個列表列印['昨夜星辰昨夜風\n', '畫樓西畔桂堂東\n', '身無彩鳳雙飛翼\n', '心有靈犀一點通']378268245344280昨夜星辰昨夜風畫樓西畔桂堂東身無彩鳳雙飛翼心有靈犀一點通遍曆方法昨夜星辰昨夜風畫樓西畔桂堂東身無彩鳳雙飛翼心有靈犀一點通

 

 

 

檔案的tell() 和 seek()方法

 樣本:

f = open('無題','r',encoding='utf8')f.read(4)print('當前游標位置',f.tell())f.seek(10)print('當前游標位置',f.tell())f.close()#read時,一個中文算三個字元

運行結果:

當前游標位置 12當前游標位置 10

 

檔案操作之flush方法

 

import sys,timefor i in range(20):    sys.stdout.write("#")    sys.stdout.flush()    time.sleep(1)

 

truncate方法 
f = open('test','w')f.write("hello")f.write("\n")f.write("python")f.flush() #這樣不用執行close方法,記憶體中的資料,就會寫入到diskf.close()f = open('test','a')f.truncate(2)  #截斷方法,游標從2開始往後截取f.close()

 

 

其他的檔案方法: r+ 讀寫方法

 

聯繫我們

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