老齊python-基礎7(檔案操作、迭代)

來源:互聯網
上載者:User

標籤:and   開始   set   images   一個   check   ...   ges   修改   

    在python3中,沒有file這個內建類型了(python2中,file是預設類型)

1、讀檔案

    建立檔案,130.txt 並在裡面輸入

learn pythonhttp://qiwsir.github.io[email protected]
>>> f = open("130.txt")>>> dir(f)  #查看方法[‘_CHUNK_SIZE‘, ‘__class__‘, ‘__del__‘, ‘__delattr__‘, ‘__dict__‘, ‘__dir__‘, ‘__doc__‘, ‘__enter__‘, ‘__eq__‘, ‘__exit__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getstate__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__next__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_checkClosed‘, ‘_checkReadable‘, ‘_checkSeekable‘, ‘_checkWritable‘, ‘_finalizing‘, ‘buffer‘, ‘close‘, ‘closed‘, ‘detach‘, ‘encoding‘, ‘errors‘, ‘fileno‘, ‘flush‘, ‘isatty‘, ‘line_buffering‘, ‘mode‘, ‘name‘, ‘newlines‘, ‘read‘, ‘readable‘, ‘readline‘, ‘readlines‘, ‘seek‘, ‘seekable‘, ‘tell‘, ‘truncate‘, ‘writable‘, ‘write‘, ‘writelines‘]

 

f = open("./codes/130.txt")  #當在上級目錄時指定檔案for line in f:    print(line)

2、建立檔案

>>> nf = open("txtfile.txt","w")  #建立txtfile.txt檔案>>> nf.write("This is a new file")  #檔案中添加一句話,並返回字串長度18>>> nf.close()   #關閉開啟的檔案

    唯讀方式測試

>>> f = open("txtfile.txt")>>> f<_io.TextIOWrapper name=‘txtfile.txt‘ mode=‘r‘ encoding=‘UTF-8‘>>>> f = open("txtfile.txt","r")>>> f<_io.TextIOWrapper name=‘txtfile.txt‘ mode=‘r‘ encoding=‘UTF-8‘>

    1)w 模式,以寫方式開啟檔案,可向檔案寫入資訊。如果檔案存在則清空檔案,再寫新內容。

    2)a 模式,以追加模式開啟檔案(一開啟檔案,檔案指標自動移到檔案末尾),如果檔案不存在則建立

       也可以用這種模式開啟一個不存在的檔案,即建立

>>> fn = open("mdfile.md","a")>>> fn<_io.TextIOWrapper name=‘mdfile.md‘ mode=‘a‘ encoding=‘UTF-8‘>>>> fn.write("python can helo you to be agreat programmer.")44>>> fn.close()

3、使用with

     在對檔案進行寫入操作之後,都要執行file.close(),它的作用就是將檔案關閉,同事也將內容儲存在檔案中。

     除了顯示的操作關閉之外,還有另外一種方法with,更加pythonic

>>> with open("mdfile.md","a") as f:...     f.write("\nI am a Pythoner.")...17

4、檔案的狀態

    有時候要擷取一個檔案的狀態(也成為屬性),比如建立日期、修改日期、大小等。

>>> import os>>> file_stat = os.stat("mdfile.md")  #使用os模組讀取檔案屬性>>> file_statos.stat_result(st_mode=33188, st_ino=8672850, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=61, st_atime=1505309783, st_mtime=1505309775, st_ctime=1505309775)>>> file_stat.st_ctime1505309775.0>>> import time    #使用time模組讀取時間>>> time.localtime(file_stat.st_ctime)time.struct_time(tm_year=2017, tm_mon=9, tm_mday=13, tm_hour=21, tm_min=36, tm_sec=15, tm_wday=2, tm_yday=256, tm_isdst=0)

5、read/readline/readlines

>>> f = open("mdfile.md")  >>> f.read(12)  #讀取前12個字元‘python can h‘>>> f.read()    #如果不指定就輸出到EOF為止(End of file)‘elo you to be agreat programmer.\nI am a Pythoner.‘   #指標的原因沒有讀取前部分

    readline,逐行讀取檔案內容

>>> f.readline()   #每執行一次讀取一行‘python can helo you to be agreat programmer.\n‘>>> f.readline()‘I am a Pythoner.‘>>> f.readline()‘‘

    readlines,將檔案各行讀出來,放到一個列表中返回

>>> f = open("mdfile.md")>>> f.readlines()[‘python can helo you to be agreat programmer.\n‘, ‘I am a Pythoner.‘]>>> f = open("mdfile.md")>>> for line in f.readlines(): print(line)...python can helo you to be agreat programmer.I am a Pythoner.>>> f = open("mdfile.md")>>> for line in f: print(line)   #看似相同其實不同,readlines已經在記憶體中產生列表...python can helo you to be agreat programmer.I am a Pythoner.

 6、讀很大的檔案

>>> import fileinput>>> for line in fileinput.input("you.md"): print(line,end=‘‘)...You Raise Me UpWhen I am down 當我失意低落之時and, oh my soul, so weary; 我的精神,是那麼疲倦不堪When troubles come 當煩惱困難襲來之際and my heart burdened be; 我的內心,是那麼負擔沉重Then, I am still 然而,我默默的佇立and wait here in the silence, 靜靜的等待Until you come 直到你的來臨and sit awhile with me. 片刻地和我在一起

7、seek

    讀取檔案,指標也隨著運動,當讀取結束時,這陣就移動了相應的位置。

>>> f = open("you.md")>>> f.readline()‘You Raise Me Up\n‘>>> f.readline()‘When I am down 當我失意低落之時\n‘>>> f.tell()            #查看指標位置56>>> f.seek(0)        #重設指標位置0>>> f.readline()‘You Raise Me Up\n‘>>> f.tell()16>>> f.readline()‘When I am down 當我失意低落之時\n‘>>> f.seek(4)       #將指標移動到對應位置4>>> f.tell()4>>> f.readline()‘Raise Me Up\n‘

     指標特性:

         seek(offset[,whence])是這個函數的完整形式,以上我們省略了whence,在預設情況下都是以檔案的開頭為參照物進行移動的,即whence=0 whence,還可以有別的值,具體:

        1)預設值是0,表示從檔案開頭開始計算指標位移的量(簡稱位移量)

        2)當whence=1,表示從當前位置開始計算位移量。

        3)當whence=2,表示相對檔案末尾移動

 

二、初始迭代

    迴圈(Loop),指的是在滿足條件的情況下,重複執行同一段代碼,如while語句。

    迭代(Iterate),指的是按照某種順序諸葛訪問對象(如列表)中的每一項,如for語句。

    遞迴(Recursion),指的是一個函數不斷調用自身的行為,如著名的斐波那契數列。

    遍曆(Traversal),指的是按照一定的規則訪問樹形結構中的每個節點,而且每個節點都只訪問一次。for迴圈就是一種遍曆。

 

老齊python-基礎7(檔案操作、迭代)

聯繫我們

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