python 學習筆記 5 -- 文件輸入輸出

本文主要介紹python下的文件輸入輸出操作,python的文件操作簡單易用~通過本文相信你可以熟練掌握file和pickle這兩種輸入輸出操作!


1.文件

你可以通過創建一個file類的對象來打開一個文件,分別使用file類的read、readline或write方法來恰當地讀寫文件。對文件的讀寫能力依賴於你在打開文件時指定的模式。

eg.

文件打開:

  1. f = file('poem.txt''w')         # 指明文件和模式來創建一個file類的實例。模式可以爲讀模式('r')、寫模式('w')或追加模式('a')。  

  2. 用的文件打開方式:    

  3. f = open('poem.txt''w')         # open方法是用來打開磁盤上的文件。open返回一個文件對象(與上句file創建實例類似),它擁有一些方法和屬性,可以得到被打開文件的信息以及對該文件進行操作。  

  4.                                   # 此外,open方法可以接收三個參數:文件名、模式和緩衝區參數。只有第一個參數(文件名)是必需的;其他兩個時可選的。如果沒有指定,文件以文本方式打開。更多關於文件的學習可以使用命令:” pydoc file ”查看、學習  



文件寫:

  1. f = file('poem.txt''w')         # 指明文件和模式來創建一個file類的實例。模式可以爲讀模式('r')、寫模式('w')或追加模式('a')。  

  2. e(poem) # 寫文件  

  3. f.close() # 關閉文件描述符  



文件讀:


  1. f = file('poem.txt'# 打開文件不指定模式則爲默認模式'r'  

  2. while True:  

  3. line = f.readline() # 讀文件中的一行,讀取一行後,下一次在使用readline就會讀下一行,以此類推直到文件結束(EOF)。我們也可以直接使用read()讀取整個文件  

  4. if len(line) == 0# 讀取的行長度爲0指的是讀到了EOF  

  5.     break  

  6. print line, # 使用逗號爲了阻止打印後自動換行  

  7. f.close()  


注: 使用readline()時,python會掃描每一個字節,知道\n,然後它會停止讀取文件並返回此前的文件內容。而 f 則會記錄每次調用readline()後的讀取位置,這樣下一次他就可以在被調用時讀取下一行數據。那麼這樣一直讀到文件結尾後我們再想使用readline讀取文件該怎麼辦? 答案是~~使用file的seek將記錄的位置挪到文件開始處!

eg.


  1. f = file('poem.txt')                # 打開文件不指定模式則爲默認模式'r'  

  2. while True:  

  3.     line = f.readline()            # 讀文件中的一行,讀取一行後,下一次在使用readline就會讀下一行,以此類推直到文件結束>(EOF)。  

  4.     if len(line) == 0:              # 讀取的行長度爲0指的是讀到了EOF  

  5.         break  

  6.     print line,                       # 使用逗號爲了阻止打印後自動換行  

  7. f.seek(0)       # 使用seek(0)將當前位置跳轉到文件開始處  

  8.                 # 文件的seek方法在被打開文件中移動到另一個位置。  

  9.                 # 第二個參數指出第一個參數是什麼意思: 0 表示移動到一個絕對位置(從文件起始處算起);1  表示移動到一個相  

  10. 置算起);2表示相對於文件尾的位置,所以seek(-1282)表示跳到從文件尾算第128個字節的位置。  

  11. f.tell()        # 文件的tell方法可以告訴你當前打開文件的當前位置。  

  12.                 # 因爲剛seek(0)跳轉到文件開始處,所以tell()會返回0,表示當前位置在文件開始處  

  13. print f.readline()                 # 仍然打印的第一行哦!  

  14. f.close()  

  15.   

  16. f = file('poem.txt''w'# 擦除文件需要用寫模式('w')打開文件  

  17. f.truncate(poem) # 擦除文件,小心使用!  

  18. f.close() # 關閉文件描述符  




文件擦除:

[python] view plaincopy在CODE上查看代碼片派生到我的代碼片

  1. f = file('poem.txt''w'# 擦除文件需要用寫模式('w')打開文件  

  2. f.truncate(poem) # 擦除文件,小心使用!  

  3. f.close() # 關閉文件描述符  




文件關閉:

  1. f.close() 上面示例中已多次用到此函數關閉文件  

  2. f.closed 文件對象的closed屬性是用來表示對象是打開還是關閉的,調用 f.closed返回True則表示已關閉,返回False則表示還未關閉!  



下面是我寫的一個對當前所學的很多python知識的一個大綜合的腳本,看看你是否已經能夠理解?

  1. #!/usr/bin/python  

  2. # -*- coding: utf-8 -*-  

  3. # 本腳本主要用於介紹文件讀寫,其中也使用了很多之前介紹到的python特性  

  4. from os.path import exists          # 使用import從os.path模塊中加載exists,關於import會在後續的博客中介紹,這裏就理解成頭文件,加載了exists後我們纔可以使用它!  

  5. from sys import argv                # 前面介紹過,接收腳本的參數需要使用argv  

  6. script ,  from_file, to_file = argv  

  7. print "coping from %s to %s" %(from_file,to_file)   # 打印出來我們這次所要做的工作  

  8.   

  9. in_file=open(from_file)             # 打開from_file文件,將open的返回值賦給in_file。注意,open文件時沒有帶模式所以使用默認讀模式  

  10. data = in_file.read()               # 讀文件內容到data  

  11. print "The input file is %s bytes long" % len(data)  

  12.   

  13. print "Does the outfile exist?\n\t %s " % exists(to_file)   # 腳本開始時import的exists函數(用來檢測文件是否存在,存在返回True)  

  14. raw_input("Ready ,Hit RETURN to continue,Ctrl-C to abort")  

  15.   

  16. out_file = open(to_file,'w')        # 使用寫模式打開to_file  

  17. out_file.write(data)                # 使用file的write函數將數據寫到目的文件中  

  18. print 'Alright ,all done'  

  19.   

  20. in_file.close()                     # 記得關閉已使用的文件  

  21. out_file.close()       

  22.       

  23. out_file = open(to_file)            # 以讀模式打開to_file,爲什麼要先關閉再打開呢?:-),你自己試試?  

  24. print " The %s file is now:" % to_file  

  25. print out_file.read()  

  26. out_file.close()                    # 再關閉讀模式  

  27.   

  28. # 下面我們測試擦除文件,擦除需要寫模式  

  29. out_file = open(to_file,'w')  

  30. raw_input("Do you want to erase the copy file ,Hit RETURN to continue,Ctrl-C to abort")  

  31. out_file.truncate()                 # 使用file的truncate()對文件進行擦除操作  

  32.   

  33. # 再寫幾串字符串到文件中  

  34. print "Now I'm going to ask you for three lines:"  

  35. line1 = raw_input("Line 1: >")       # 對raw_input還熟悉不?它主要用來接受用戶輸入,而它帶的參數可以打印到屏幕上作爲提示!  

  36. line2 = raw_input("Line 2: >")       # raw_input 是不是很好用?  

  37. line3 = raw_input("Line 3: >")  

  38.   

  39. print "Now I'm going to write these three lines to the %r file" % to_file  

  40. out_file.write(line1+"\n"+line2+"\n"+line3+"\n")    # 直接使用+鏈接幾個字符串並寫入文件!  

  41. print "write done "  

  42.   

  43. out_file.close()  

  44.   

  45. out_file = open(to_file)            # 再打開讀一下看看此時的to_file文件內容!  

  46. print " The %s file is now:" % to_file  

  47. print out_file.read()  

  48. out_file.close()  

運行起來是這樣的!這裏的poem.txt是我早已準備好的文件!

  1. # python file_test.py poem.txt /tmp/poem  

  2. coping from poem.txt to /tmp/poem  

  3. The input file is 104 bytes long  

  4. Does the outfile exist?  

  5.      False   

  6. Ready ,Hit RETURN to continue,Ctrl-C to abort  

  7. Alright ,all done  

  8.  The /tmp/poem file is now:  

  9. This is the python poem   

  10. using for txt read   

  11. do you like me?  

  12. whatever  

  13. I like myself   

  14. I'm selfconfidence  

  15.   

  16. Do you want to erase the copy file ,Hit RETURN to continue,Ctrl-C to abort  

  17. Now I'm going to ask you for three lines:  

  18. Line 1: >the first line I write  

  19. Line 2: >second line to read  

  20. Line 3: >what ? the third line ?  

  21. Now I'm going to write these three lines to the '/tmp/poem' file  

  22. write done   

  23.  The /tmp/poem file is now:  

  24. the first line I write  

  25. second line to read  

  26. what ? the third line ?  

2.儲存器

Python提供一個標準的模塊,稱爲pickle。使用pickle你可以在一個文件中儲存任何Python對象,之後你又可以把它完整無缺地取出來。這被稱爲 持久地 儲存對象。(還有另一個模塊稱爲cPickle,它的功能和pickle模塊完全相同,只不過它是用C語言編寫的,因此要快得多(比pickle快1000倍)。你可以使用它們中的任一個,而我們在這裏將使用cPickle模塊。記住,我們把這兩個模塊都簡稱爲pickle模塊。)

eg.

  1. #!/usr/bin/python  

  2. # -*- coding: utf-8 -*-  

  3.   

  4. import cPickle as p     # import..as語法是一種便利方法,以便於我們可以使用更短的模塊名稱。在程序的其餘部>分的時候,我們簡單地把這個模塊稱爲p。  

  5.   

  6. shoplist = ['apple''mango']   # 一個列表,用來作爲演示存儲  

  7. shoplistfile = 'shoplist.data'  # 指定一個文件名  

  8.   

  9. f = file(shoplistfile, 'w')     # 使用寫模式打開  

  10. p.dump(shoplist, f)             # 將列表中的信息dump到文件中,調用pickle模塊的dump函數,把對象儲存到打開的文件中。這個過程稱爲 儲存 。  

  11. f.close()                       # 關閉文件  

  12. print "Dump success ,Now I will read the data in the file"  

  13. f = file(shoplistfile)          # 讀模式打開文件  

  14. data = p.load(f)                # 使用pickle模塊的load函數的返回來取回對象。這個過程稱爲 取儲存  

  15. print data                      # 打印取存儲信息  





其實它和文件讀寫也比較相像,下面是運行的狀況:

  1. long@zhouyl:/tmp$ python pickle.py  

  2. Dump success ,Now I will read the data in the file  

  3. ['apple''mango']  

  4. long@zhouyl:/tmp$ cat shoplist.data  

  5. (lp1  

  6. S'apple'  

  7. p2  

  8. aS'mango'  

  9. p3  



所以我們可以看到,使用pickle存儲到文件中的和直接寫入到文件中的內容時不一樣的,所以千萬不要兩種方法混合使用(使用pickle.dump存儲的內容一定要使用load取出,不要使用file.read())!否則就會出現如下狀況:

  1. Now I will read the data in the file with file.read()  

  2. (lp1  

  3. S'apple'  

  4. p2  

  5. aS'mango'  

  6. p3  

  7. a.  


對於文件讀寫,需要考慮文件打開、讀寫錯誤等問題,需要添加異常處理部分(請將下篇)。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章