本文主要介紹python下的文件輸入輸出操作,python的文件操作簡單易用~通過本文相信你可以熟練掌握file和pickle這兩種輸入輸出操作!
1.文件
你可以通過創建一個file類的對象來打開一個文件,分別使用file類的read、readline或write方法來恰當地讀寫文件。對文件的讀寫能力依賴於你在打開文件時指定的模式。
eg.
文件打開:
f = file('poem.txt', 'w') # 指明文件和模式來創建一個file類的實例。模式可以爲讀模式('r')、寫模式('w')或追加模式('a')。
用的文件打開方式:
f = open('poem.txt', 'w') # open方法是用來打開磁盤上的文件。open返回一個文件對象(與上句file創建實例類似),它擁有一些方法和屬性,可以得到被打開文件的信息以及對該文件進行操作。
# 此外,open方法可以接收三個參數:文件名、模式和緩衝區參數。只有第一個參數(文件名)是必需的;其他兩個時可選的。如果沒有指定,文件以文本方式打開。更多關於文件的學習可以使用命令:” pydoc file ”查看、學習
文件寫:
f = file('poem.txt', 'w') # 指明文件和模式來創建一個file類的實例。模式可以爲讀模式('r')、寫模式('w')或追加模式('a')。
e(poem) # 寫文件
f.close() # 關閉文件描述符
文件讀:
f = file('poem.txt') # 打開文件不指定模式則爲默認模式'r'
while True:
line = f.readline() # 讀文件中的一行,讀取一行後,下一次在使用readline就會讀下一行,以此類推直到文件結束(EOF)。我們也可以直接使用read()讀取整個文件
if len(line) == 0: # 讀取的行長度爲0指的是讀到了EOF
break
print line, # 使用逗號爲了阻止打印後自動換行
f.close()
注: 使用readline()時,python會掃描每一個字節,知道\n,然後它會停止讀取文件並返回此前的文件內容。而 f 則會記錄每次調用readline()後的讀取位置,這樣下一次他就可以在被調用時讀取下一行數據。那麼這樣一直讀到文件結尾後我們再想使用readline讀取文件該怎麼辦? 答案是~~使用file的seek將記錄的位置挪到文件開始處!
eg.
f = file('poem.txt') # 打開文件不指定模式則爲默認模式'r'
while True:
line = f.readline() # 讀文件中的一行,讀取一行後,下一次在使用readline就會讀下一行,以此類推直到文件結束>(EOF)。
if len(line) == 0: # 讀取的行長度爲0指的是讀到了EOF
break
print line, # 使用逗號爲了阻止打印後自動換行
f.seek(0) # 使用seek(0)將當前位置跳轉到文件開始處
# 文件的seek方法在被打開文件中移動到另一個位置。
# 第二個參數指出第一個參數是什麼意思: 0 表示移動到一個絕對位置(從文件起始處算起);1 表示移動到一個相
置算起);2表示相對於文件尾的位置,所以seek(-128,2)表示跳到從文件尾算第128個字節的位置。
f.tell() # 文件的tell方法可以告訴你當前打開文件的當前位置。
# 因爲剛seek(0)跳轉到文件開始處,所以tell()會返回0,表示當前位置在文件開始處
print f.readline() # 仍然打印的第一行哦!
f.close()
f = file('poem.txt', 'w') # 擦除文件需要用寫模式('w')打開文件
f.truncate(poem) # 擦除文件,小心使用!
f.close() # 關閉文件描述符
文件擦除:
[python] view plaincopy
f = file('poem.txt', 'w') # 擦除文件需要用寫模式('w')打開文件
f.truncate(poem) # 擦除文件,小心使用!
f.close() # 關閉文件描述符
文件關閉:
f.close() 上面示例中已多次用到此函數關閉文件
f.closed 文件對象的closed屬性是用來表示對象是打開還是關閉的,調用 f.closed返回True則表示已關閉,返回False則表示還未關閉!
下面是我寫的一個對當前所學的很多python知識的一個大綜合的腳本,看看你是否已經能夠理解?
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 本腳本主要用於介紹文件讀寫,其中也使用了很多之前介紹到的python特性
from os.path import exists # 使用import從os.path模塊中加載exists,關於import會在後續的博客中介紹,這裏就理解成頭文件,加載了exists後我們纔可以使用它!
from sys import argv # 前面介紹過,接收腳本的參數需要使用argv
script , from_file, to_file = argv
print "coping from %s to %s" %(from_file,to_file) # 打印出來我們這次所要做的工作
in_file=open(from_file) # 打開from_file文件,將open的返回值賦給in_file。注意,open文件時沒有帶模式所以使用默認讀模式
data = in_file.read() # 讀文件內容到data
print "The input file is %s bytes long" % len(data)
print "Does the outfile exist?\n\t %s " % exists(to_file) # 腳本開始時import的exists函數(用來檢測文件是否存在,存在返回True)
raw_input("Ready ,Hit RETURN to continue,Ctrl-C to abort")
out_file = open(to_file,'w') # 使用寫模式打開to_file
out_file.write(data) # 使用file的write函數將數據寫到目的文件中
print 'Alright ,all done'
in_file.close() # 記得關閉已使用的文件
out_file.close()
out_file = open(to_file) # 以讀模式打開to_file,爲什麼要先關閉再打開呢?:-),你自己試試?
print " The %s file is now:" % to_file
print out_file.read()
out_file.close() # 再關閉讀模式
# 下面我們測試擦除文件,擦除需要寫模式
out_file = open(to_file,'w')
raw_input("Do you want to erase the copy file ,Hit RETURN to continue,Ctrl-C to abort")
out_file.truncate() # 使用file的truncate()對文件進行擦除操作
# 再寫幾串字符串到文件中
print "Now I'm going to ask you for three lines:"
line1 = raw_input("Line 1: >") # 對raw_input還熟悉不?它主要用來接受用戶輸入,而它帶的參數可以打印到屏幕上作爲提示!
line2 = raw_input("Line 2: >") # raw_input 是不是很好用?
line3 = raw_input("Line 3: >")
print "Now I'm going to write these three lines to the %r file" % to_file
out_file.write(line1+"\n"+line2+"\n"+line3+"\n") # 直接使用+鏈接幾個字符串並寫入文件!
print "write done "
out_file.close()
out_file = open(to_file) # 再打開讀一下看看此時的to_file文件內容!
print " The %s file is now:" % to_file
print out_file.read()
out_file.close()
運行起來是這樣的!這裏的poem.txt是我早已準備好的文件!
# python file_test.py poem.txt /tmp/poem
coping from poem.txt to /tmp/poem
The input file is 104 bytes long
Does the outfile exist?
False
Ready ,Hit RETURN to continue,Ctrl-C to abort
Alright ,all done
The /tmp/poem file is now:
This is the python poem
using for txt read
do you like me?
whatever
I like myself
I'm selfconfidence
Do you want to erase the copy file ,Hit RETURN to continue,Ctrl-C to abort
Now I'm going to ask you for three lines:
Line 1: >the first line I write
Line 2: >second line to read
Line 3: >what ? the third line ?
Now I'm going to write these three lines to the '/tmp/poem' file
write done
The /tmp/poem file is now:
the first line I write
second line to read
what ? the third line ?
Python提供一個標準的模塊,稱爲pickle。使用pickle你可以在一個文件中儲存任何Python對象,之後你又可以把它完整無缺地取出來。這被稱爲 持久地 儲存對象。(還有另一個模塊稱爲cPickle,它的功能和pickle模塊完全相同,只不過它是用C語言編寫的,因此要快得多(比pickle快1000倍)。你可以使用它們中的任一個,而我們在這裏將使用cPickle模塊。記住,我們把這兩個模塊都簡稱爲pickle模塊。)
eg.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cPickle as p # import..as語法是一種便利方法,以便於我們可以使用更短的模塊名稱。在程序的其餘部>分的時候,我們簡單地把這個模塊稱爲p。
shoplist = ['apple', 'mango'] # 一個列表,用來作爲演示存儲
shoplistfile = 'shoplist.data' # 指定一個文件名
f = file(shoplistfile, 'w') # 使用寫模式打開
p.dump(shoplist, f) # 將列表中的信息dump到文件中,調用pickle模塊的dump函數,把對象儲存到打開的文件中。這個過程稱爲 儲存 。
f.close() # 關閉文件
print "Dump success ,Now I will read the data in the file"
f = file(shoplistfile) # 讀模式打開文件
data = p.load(f) # 使用pickle模塊的load函數的返回來取回對象。這個過程稱爲 取儲存
print data # 打印取存儲信息
其實它和文件讀寫也比較相像,下面是運行的狀況:
long@zhouyl:/tmp$ python pickle.py
Dump success ,Now I will read the data in the file
['apple', 'mango']
long@zhouyl:/tmp$ cat shoplist.data
(lp1
S'apple'
p2
aS'mango'
p3
所以我們可以看到,使用pickle存儲到文件中的和直接寫入到文件中的內容時不一樣的,所以千萬不要兩種方法混合使用(使用pickle.dump存儲的內容一定要使用load取出,不要使用file.read())!否則就會出現如下狀況:
Now I will read the data in the file with file.read()
(lp1
S'apple'
p2
aS'mango'
p3
a.
對於文件讀寫,需要考慮文件打開、讀寫錯誤等問題,需要添加異常處理部分(請將下篇)。