python文件读写2
生活随笔
收集整理的這篇文章主要介紹了
python文件读写2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最基本的文件操作當然就是在文件中讀寫數據。這也是很容易掌握的?,F在打開一個文件以進行寫操作:?
1. fileHandle = open ( 'test.txt', 'w' )??
fileHandle = open ( 'test.txt', 'w' )?
‘w'是指文件將被寫入數據,語句的其它部分很好理解。下一步就是將數據寫入文件:?
1. fileHandle.write ( 'This is a test.\nReally, it is.' )??
fileHandle.write ( 'This is a test.\nReally, it is.' )?
這個語句將“This is a test.”寫入文件的第一行,“Really, it is.”寫入文件的第二行。最后,我們需要做清理工作,并且關閉文件:?
1. fileHandle.close()??
fileHandle.close()?
正如你所見,在Python的面向對象機制下,這確實非常簡單。需要注意的是,當你再次使用“w”方式在文件中寫數據,所有原來的內容都會被刪除。如果想保留原來的內容,可以使用“a”方式在文件中結尾附加數據:?
1. fileHandle = open ( 'test.txt', 'a' )??
2. fileHandle.write ( '\n\nBottom line.' )??
3. fileHandle.close()??
fileHandle = open ( 'test.txt', 'a' )?
fileHandle.write ( '\n\nBottom line.' )?
fileHandle.close()?
然后,我們讀取test.txt,并將內容顯示出來:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.read()??
3. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
print fileHandle.read()?
fileHandle.close()?
以上語句將讀取整個文件并顯示其中的數據。我們也可以讀取文件中的一行:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.readline() # "This is a test."??
3. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
同時,也可以將文件內容保存到一個list中:?
1. fileHandle = open ( 'test.txt' )??
2. fileList = fileHandle.readlines()<div></div>??
3. for fileLine in fileList:??
4.???? print '>>', fileLine??
5. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
fileList = fileHandle.readlines()?
for fileLine in fileList:?
print '>>', fileLine?
fileHandle.close()?
Python在讀取一個文件時,會記住其在文件中的位置,如下所示:?
1. fileHandle = open ( 'test.txt' )??
2. garbage = fileHandle.readline()??
3. fileHandle.readline() # "Really, it is."fileHandle.close()??
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.readline() # "Really, it is."fileHandle.close()?
可以看到,只有第二行顯示出來。然而,我們可以讓Python從頭開始讀來解決這個問題:?
1. fileHandle = open ( 'test.txt' )??
2. garbage = fileHandle.readline()??
3. fileHandle.seek ( 0 )??
4. print fileHandle.readline() # "This is a test."??
5. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.seek ( 0 )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
在上面這個例子中,我們讓Python從文件第一個字節開始讀取數據。所以,第一行文字顯示了出來。當然,我們也可以獲取Python在文件中的位置:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.readline() # "This is a test."??
3. print fileHandle.tell() # "17"??
4. print fileHandle.readline() # "Really, it is."??
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
print fileHandle.tell() # "17"?
print fileHandle.readline() # "Really, it is."?
或者在文件中一次讀取幾個字節的內容:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.read ( 1 ) # "T"??
3. fileHandle.seek ( 4 )??
4. print FileHandle.read ( 1 ) # " "(原文有錯)??
fileHandle = open ( 'test.txt' )?
print fileHandle.read ( 1 ) # "T"?
fileHandle.seek ( 4 )?
print FileHandle.read ( 1 ) # " "(原文有錯)?
在Windows和Macintosh環境下,有時可能需要以二進制方式讀寫文件,比如圖片和可執行文件。此時,只要在打開文件的方式參數中增加一個“b”即可:?
1. fileHandle = open ( 'testBinary.txt', 'wb' )??
2. fileHandle.write ( 'There is no spoon.' )??
3. fileHandle.close()??
fileHandle = open ( 'testBinary.txt', 'wb' )?
fileHandle.write ( 'There is no spoon.' )?
fileHandle.close()?
1. fileHandle = open ( 'testBinary.txt', 'rb' )??
2. print fileHandle.read()??
3. fileHandle.close()??
fileHandle = open ( 'testBinary.txt', 'rb' )?
print fileHandle.read()?
fileHandle.close()?
二、從現有文件中獲取信息?
使用Python中的模塊,可以從現有文件中獲取信息。使用“os”模塊和“stat”模塊可以獲取文件的基本信息:?
1. import os??
2. import stat??
3. import time<div></div>??
4.???
5. fileStats = os.stat ( 'test.txt' )??
6. fileInfo = {??
7.???? 'Size' : fileStats [ stat.ST_SIZE ],??
8.???? 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),??
9.???? 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),??
10.???? 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),??
11.???? 'Mode' : fileStats [ stat.ST_MODE ]??
12. }??
13.???
14. for infoField, infoValue in fileInfo:??
15.???? print infoField, ':' + infoValue??
16. if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):??
17.???? print 'Directory. '??
18. else:??
19.???? print 'Non-directory.'??
import os?
import stat?
import time?
fileStats = os.stat ( 'test.txt' )?
fileInfo = {?
'Size' : fileStats [ stat.ST_SIZE ],?
'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),?
'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),?
'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),?
'Mode' : fileStats [ stat.ST_MODE ]?
}?
for infoField, infoValue in fileInfo:?
print infoField, ':' + infoValue?
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory. '?
else:?
print 'Non-directory.'?
上面這個例子創建了一個包含文件基本信息的dictionary。然后顯示了相關信息,并且告訴我們打開的是否為目錄。我們也可以試一下打開的是否是其它幾種類型:?
1. import os??
2. import stat??
3.???
4. fileStats = os.stat ( 'test.txt' )??
5. fileMode = fileStats [ stat.ST_MODE ]??
6. if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):??
7.???? print 'Regular file.'??
8. elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):??
9.???? print 'Directory.'??
10. elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):??
11.???? print 'Shortcut.'??
12. elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):??
13.???? print 'Socket.'??
14. elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):??
15.???? print 'Named pipe.'??
16. elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):??
17.???? print 'Block special device.'??
18. elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):??
19.???? print 'Character special device.'??
import os?
import stat?
fileStats = os.stat ( 'test.txt' )?
fileMode = fileStats [ stat.ST_MODE ]?
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):?
print 'Regular file.'?
elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory.'?
elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):?
print 'Shortcut.'?
elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):?
print 'Socket.'?
elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):?
print 'Named pipe.'?
elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):?
print 'Block special device.'?
elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):?
print 'Character special device.'?
另外,我們可以使用“os.path”來獲取基本信息:?
1. import os.path??
2.???
3. fileStats = 'test.txt'??
4. if os.path.isdir ( fileStats ):??
5.???? print 'Directory.'??
6. elif os.path.isfile ( fileStats ):??
7.???? print 'File.'??
8. elif os.path.islink ( fileStats ):??
9.???? print 'Shortcut.'??
10. elif os.path.ismount ( fileStats ):??
11.???? print 'Mount point.'??
import os.path?
fileStats = 'test.txt'?
if os.path.isdir ( fileStats ):?
print 'Directory.'?
elif os.path.isfile ( fileStats ):?
print 'File.'?
elif os.path.islink ( fileStats ):?
print 'Shortcut.'?
elif os.path.ismount ( fileStats ):?
print 'Mount point.'?
三、目錄?
和普通文件一樣,關于目錄的操作也很容易掌握。首先,列出一個目錄的內容:?
1. import os??
2.???
3. for fileName in os.listdir ( '/' ):??
4.???? print fileName??
import os?
for fileName in os.listdir ( '/' ):?
print fileName?
正如你所見,這很簡單,用三行代碼就可以完成。?
創建目錄也很簡單:?
1. import os??
2.???
3. os.mkdir ( 'testDirectory' )??
import os?
os.mkdir ( 'testDirectory' )?
刪除剛才創建的目錄:?
1. import os??
2.???
3. os.rmdir ( 'testDirectory )??
import os?
os.rmdir ( 'testDirectory )?
嗯,可以創建多級目錄:?
1. import os??
2.???
3. os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )??
import os?
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
如果沒有在創建的文件夾中添加任何東西,就可以一次性將它們全部刪除(即,刪除所列的所有空文件夾):?
1. import os??
2.???
3. os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )??
import os?
os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
當需要對一個特定的文件類型進行操作時,我們可以選擇“fnmatch”模塊。以下是顯示“.txt”文件的內容和“.exe”文件的文件名:?
1. import fnmatch??
2. import os??
3.???
4. for fileName in os.listdir ( '/' ):??
5.???? if fnmatch.fnmath ( fileName, '*.txt' ):??
6.???????? print open ( fileName ).read()??
7.???? elif fnmatch.fnmatch ( fileName, '*.exe' ):??
8.???????? print fileName??
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmath ( fileName, '*.txt' ):?
print open ( fileName ).read()?
elif fnmatch.fnmatch ( fileName, '*.exe' ):?
print fileName?
“*”字符可以表示任意長度的字符。如果要匹配一個字符,則使用“?”符號:?
1. import fnmatch??
2. import os??
3.???
4. for fileName in os.listdir ( '/' ):??
5.???? if fnmatch.fnmatch ( fileName, '?.txt' ):??
6.???????? print 'Text file.'??
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmatch ( fileName, '?.txt' ):?
print 'Text file.'?
“fnmatch”模塊支持正則表達式:?
1. import fnmatch??
2. import os??
3. import re??
4.???
5. filePattern = fnmatch.translate ( '*.txt' )??
6. for fileName in os.listdir ( '/' ):??
7.???? if re.match ( filePattern, fileName ):??
8.???????? print 'Text file.'??
import fnmatch?
import os?
import re?
filePattern = fnmatch.translate ( '*.txt' )?
for fileName in os.listdir ( '/' ):?
if re.match ( filePattern, fileName ):?
print 'Text file.'?
若只需要匹配一種類型的文件,更好的辦法是使用“glob”模塊。該模塊的格式和“fnmatch”相似:?
1. import glob??
2.???
3. for fileName in glob.glob ( '*.txt' ):??
4.???? print 'Text file.'??
import glob?
for fileName in glob.glob ( '*.txt' ):?
print 'Text file.'?
使用一定范圍的字符來匹配同樣可行,就像在正則表達式中使用一樣。假設你想要顯示擴展名前只有一位數字的文件的文件名:?
1. import glob??
2.???
3. for fileName in glob.glob ( '[0-9].txt' ):??
4.???? print filename??
import glob?
for fileName in glob.glob ( '[0-9].txt' ):?
print filename?
“glob”模塊利用“fnmatch”模塊來實現。?
四、數據編組?
使用前一節中介紹的模塊,可以實現在文件中對字符串的讀寫。?
然而,有的時候,你可能需要傳遞其它類型的數據,如list、tuple、dictionary和其它對象。在Python中,你可以使用Pickling來完成。你可以使用Python標準庫中的“pickle”模塊完成數據編組。?
下面,我們來編組一個包含字符串和數字的list:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]??
5. pickle.dump ( testList, fileHandle )??
6. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
拆分編組同樣不難:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt' )??
4. testList = pickle.load ( fileHandle )??
5. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
現在試試存儲更加復雜的數據:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]??
5. pickle.dump ( testList, fileHandle )??
6. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt' )??
4. testList = pickle.load ( fileHandle )??
5. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
如上所述,使用Python的“pickle”模塊編組確實很簡單。眾多對象可以通過它來存儲到文件中。如果可以的話,“cPickle”同樣勝任這個工作。它和“pickle”模塊一樣,但是速度更快:?
1. import cPickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. cPickle.dump ( 1776, fileHandle )??
5. fileHandle.close()??
import cPickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
cPickle.dump ( 1776, fileHandle )?
fileHandle.close()?
五、創建“虛擬”文件?
你用到的許多模塊包含需要文件對象作為參數的方法。但是,有時創建并使用一個真實的文件并讓人感到有些麻煩。所幸的是,在Python中,你可以使用“StringIO”模塊來創建文件并將其保存在內存中:?
1. import StringIO??
2.???
3. fileHandle = StringIO.StringIO ( "Let freedom ring" )??
4. print fileHandle.read() # "Let freedom ring."??
5. fileHandle.close()??
import StringIO?
fileHandle = StringIO.StringIO ( "Let freedom ring" )?
print fileHandle.read() # "Let freedom ring."?
fileHandle.close()?
cStringIO”模塊同樣有效。它的使用方法和“StringIO”一樣,但就像“cPickle”之于“pickle”,它速度更快:?
1. import cStringIO??
2.???
3. fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )??
4. print fileHandle.read() # "To Kill a Mockingbid"??
5. fileHandle.close()??
import cStringIO?
fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )?
print fileHandle.read() # "To Kill a Mockingbid"?
fileHandle.close()?
結論?
文件管理,是眾多編程語言的程序員在編寫應用程序是經常遇到的問題。幸好,和其它語言相比,Python使其出乎意料地容易。Python的標準庫中提供了許多相關的模塊幫助程序員解決這方面的問題,而它的面向對象的機制也簡化了操作。?
好了,現在你已經了解了Python中文件管理的基本知識,可以在今后的應用程序中很好地使用了。?
1. fileHandle = open ( 'test.txt', 'w' )??
fileHandle = open ( 'test.txt', 'w' )?
‘w'是指文件將被寫入數據,語句的其它部分很好理解。下一步就是將數據寫入文件:?
1. fileHandle.write ( 'This is a test.\nReally, it is.' )??
fileHandle.write ( 'This is a test.\nReally, it is.' )?
這個語句將“This is a test.”寫入文件的第一行,“Really, it is.”寫入文件的第二行。最后,我們需要做清理工作,并且關閉文件:?
1. fileHandle.close()??
fileHandle.close()?
正如你所見,在Python的面向對象機制下,這確實非常簡單。需要注意的是,當你再次使用“w”方式在文件中寫數據,所有原來的內容都會被刪除。如果想保留原來的內容,可以使用“a”方式在文件中結尾附加數據:?
1. fileHandle = open ( 'test.txt', 'a' )??
2. fileHandle.write ( '\n\nBottom line.' )??
3. fileHandle.close()??
fileHandle = open ( 'test.txt', 'a' )?
fileHandle.write ( '\n\nBottom line.' )?
fileHandle.close()?
然后,我們讀取test.txt,并將內容顯示出來:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.read()??
3. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
print fileHandle.read()?
fileHandle.close()?
以上語句將讀取整個文件并顯示其中的數據。我們也可以讀取文件中的一行:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.readline() # "This is a test."??
3. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
同時,也可以將文件內容保存到一個list中:?
1. fileHandle = open ( 'test.txt' )??
2. fileList = fileHandle.readlines()<div></div>??
3. for fileLine in fileList:??
4.???? print '>>', fileLine??
5. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
fileList = fileHandle.readlines()?
for fileLine in fileList:?
print '>>', fileLine?
fileHandle.close()?
Python在讀取一個文件時,會記住其在文件中的位置,如下所示:?
1. fileHandle = open ( 'test.txt' )??
2. garbage = fileHandle.readline()??
3. fileHandle.readline() # "Really, it is."fileHandle.close()??
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.readline() # "Really, it is."fileHandle.close()?
可以看到,只有第二行顯示出來。然而,我們可以讓Python從頭開始讀來解決這個問題:?
1. fileHandle = open ( 'test.txt' )??
2. garbage = fileHandle.readline()??
3. fileHandle.seek ( 0 )??
4. print fileHandle.readline() # "This is a test."??
5. fileHandle.close()??
fileHandle = open ( 'test.txt' )?
garbage = fileHandle.readline()?
fileHandle.seek ( 0 )?
print fileHandle.readline() # "This is a test."?
fileHandle.close()?
在上面這個例子中,我們讓Python從文件第一個字節開始讀取數據。所以,第一行文字顯示了出來。當然,我們也可以獲取Python在文件中的位置:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.readline() # "This is a test."??
3. print fileHandle.tell() # "17"??
4. print fileHandle.readline() # "Really, it is."??
fileHandle = open ( 'test.txt' )?
print fileHandle.readline() # "This is a test."?
print fileHandle.tell() # "17"?
print fileHandle.readline() # "Really, it is."?
或者在文件中一次讀取幾個字節的內容:?
1. fileHandle = open ( 'test.txt' )??
2. print fileHandle.read ( 1 ) # "T"??
3. fileHandle.seek ( 4 )??
4. print FileHandle.read ( 1 ) # " "(原文有錯)??
fileHandle = open ( 'test.txt' )?
print fileHandle.read ( 1 ) # "T"?
fileHandle.seek ( 4 )?
print FileHandle.read ( 1 ) # " "(原文有錯)?
在Windows和Macintosh環境下,有時可能需要以二進制方式讀寫文件,比如圖片和可執行文件。此時,只要在打開文件的方式參數中增加一個“b”即可:?
1. fileHandle = open ( 'testBinary.txt', 'wb' )??
2. fileHandle.write ( 'There is no spoon.' )??
3. fileHandle.close()??
fileHandle = open ( 'testBinary.txt', 'wb' )?
fileHandle.write ( 'There is no spoon.' )?
fileHandle.close()?
1. fileHandle = open ( 'testBinary.txt', 'rb' )??
2. print fileHandle.read()??
3. fileHandle.close()??
fileHandle = open ( 'testBinary.txt', 'rb' )?
print fileHandle.read()?
fileHandle.close()?
二、從現有文件中獲取信息?
使用Python中的模塊,可以從現有文件中獲取信息。使用“os”模塊和“stat”模塊可以獲取文件的基本信息:?
1. import os??
2. import stat??
3. import time<div></div>??
4.???
5. fileStats = os.stat ( 'test.txt' )??
6. fileInfo = {??
7.???? 'Size' : fileStats [ stat.ST_SIZE ],??
8.???? 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),??
9.???? 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),??
10.???? 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),??
11.???? 'Mode' : fileStats [ stat.ST_MODE ]??
12. }??
13.???
14. for infoField, infoValue in fileInfo:??
15.???? print infoField, ':' + infoValue??
16. if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):??
17.???? print 'Directory. '??
18. else:??
19.???? print 'Non-directory.'??
import os?
import stat?
import time?
fileStats = os.stat ( 'test.txt' )?
fileInfo = {?
'Size' : fileStats [ stat.ST_SIZE ],?
'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),?
'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),?
'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),?
'Mode' : fileStats [ stat.ST_MODE ]?
}?
for infoField, infoValue in fileInfo:?
print infoField, ':' + infoValue?
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory. '?
else:?
print 'Non-directory.'?
上面這個例子創建了一個包含文件基本信息的dictionary。然后顯示了相關信息,并且告訴我們打開的是否為目錄。我們也可以試一下打開的是否是其它幾種類型:?
1. import os??
2. import stat??
3.???
4. fileStats = os.stat ( 'test.txt' )??
5. fileMode = fileStats [ stat.ST_MODE ]??
6. if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):??
7.???? print 'Regular file.'??
8. elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):??
9.???? print 'Directory.'??
10. elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):??
11.???? print 'Shortcut.'??
12. elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):??
13.???? print 'Socket.'??
14. elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):??
15.???? print 'Named pipe.'??
16. elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):??
17.???? print 'Block special device.'??
18. elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):??
19.???? print 'Character special device.'??
import os?
import stat?
fileStats = os.stat ( 'test.txt' )?
fileMode = fileStats [ stat.ST_MODE ]?
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):?
print 'Regular file.'?
elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):?
print 'Directory.'?
elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):?
print 'Shortcut.'?
elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):?
print 'Socket.'?
elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):?
print 'Named pipe.'?
elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):?
print 'Block special device.'?
elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):?
print 'Character special device.'?
另外,我們可以使用“os.path”來獲取基本信息:?
1. import os.path??
2.???
3. fileStats = 'test.txt'??
4. if os.path.isdir ( fileStats ):??
5.???? print 'Directory.'??
6. elif os.path.isfile ( fileStats ):??
7.???? print 'File.'??
8. elif os.path.islink ( fileStats ):??
9.???? print 'Shortcut.'??
10. elif os.path.ismount ( fileStats ):??
11.???? print 'Mount point.'??
import os.path?
fileStats = 'test.txt'?
if os.path.isdir ( fileStats ):?
print 'Directory.'?
elif os.path.isfile ( fileStats ):?
print 'File.'?
elif os.path.islink ( fileStats ):?
print 'Shortcut.'?
elif os.path.ismount ( fileStats ):?
print 'Mount point.'?
三、目錄?
和普通文件一樣,關于目錄的操作也很容易掌握。首先,列出一個目錄的內容:?
1. import os??
2.???
3. for fileName in os.listdir ( '/' ):??
4.???? print fileName??
import os?
for fileName in os.listdir ( '/' ):?
print fileName?
正如你所見,這很簡單,用三行代碼就可以完成。?
創建目錄也很簡單:?
1. import os??
2.???
3. os.mkdir ( 'testDirectory' )??
import os?
os.mkdir ( 'testDirectory' )?
刪除剛才創建的目錄:?
1. import os??
2.???
3. os.rmdir ( 'testDirectory )??
import os?
os.rmdir ( 'testDirectory )?
嗯,可以創建多級目錄:?
1. import os??
2.???
3. os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )??
import os?
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
如果沒有在創建的文件夾中添加任何東西,就可以一次性將它們全部刪除(即,刪除所列的所有空文件夾):?
1. import os??
2.???
3. os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )??
import os?
os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )?
當需要對一個特定的文件類型進行操作時,我們可以選擇“fnmatch”模塊。以下是顯示“.txt”文件的內容和“.exe”文件的文件名:?
1. import fnmatch??
2. import os??
3.???
4. for fileName in os.listdir ( '/' ):??
5.???? if fnmatch.fnmath ( fileName, '*.txt' ):??
6.???????? print open ( fileName ).read()??
7.???? elif fnmatch.fnmatch ( fileName, '*.exe' ):??
8.???????? print fileName??
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmath ( fileName, '*.txt' ):?
print open ( fileName ).read()?
elif fnmatch.fnmatch ( fileName, '*.exe' ):?
print fileName?
“*”字符可以表示任意長度的字符。如果要匹配一個字符,則使用“?”符號:?
1. import fnmatch??
2. import os??
3.???
4. for fileName in os.listdir ( '/' ):??
5.???? if fnmatch.fnmatch ( fileName, '?.txt' ):??
6.???????? print 'Text file.'??
import fnmatch?
import os?
for fileName in os.listdir ( '/' ):?
if fnmatch.fnmatch ( fileName, '?.txt' ):?
print 'Text file.'?
“fnmatch”模塊支持正則表達式:?
1. import fnmatch??
2. import os??
3. import re??
4.???
5. filePattern = fnmatch.translate ( '*.txt' )??
6. for fileName in os.listdir ( '/' ):??
7.???? if re.match ( filePattern, fileName ):??
8.???????? print 'Text file.'??
import fnmatch?
import os?
import re?
filePattern = fnmatch.translate ( '*.txt' )?
for fileName in os.listdir ( '/' ):?
if re.match ( filePattern, fileName ):?
print 'Text file.'?
若只需要匹配一種類型的文件,更好的辦法是使用“glob”模塊。該模塊的格式和“fnmatch”相似:?
1. import glob??
2.???
3. for fileName in glob.glob ( '*.txt' ):??
4.???? print 'Text file.'??
import glob?
for fileName in glob.glob ( '*.txt' ):?
print 'Text file.'?
使用一定范圍的字符來匹配同樣可行,就像在正則表達式中使用一樣。假設你想要顯示擴展名前只有一位數字的文件的文件名:?
1. import glob??
2.???
3. for fileName in glob.glob ( '[0-9].txt' ):??
4.???? print filename??
import glob?
for fileName in glob.glob ( '[0-9].txt' ):?
print filename?
“glob”模塊利用“fnmatch”模塊來實現。?
四、數據編組?
使用前一節中介紹的模塊,可以實現在文件中對字符串的讀寫。?
然而,有的時候,你可能需要傳遞其它類型的數據,如list、tuple、dictionary和其它對象。在Python中,你可以使用Pickling來完成。你可以使用Python標準庫中的“pickle”模塊完成數據編組。?
下面,我們來編組一個包含字符串和數字的list:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]??
5. pickle.dump ( testList, fileHandle )??
6. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
拆分編組同樣不難:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt' )??
4. testList = pickle.load ( fileHandle )??
5. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
現在試試存儲更加復雜的數據:?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]??
5. pickle.dump ( testList, fileHandle )??
6. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]?
pickle.dump ( testList, fileHandle )?
fileHandle.close()?
1. import pickle??
2.???
3. fileHandle = open ( 'pickleFile.txt' )??
4. testList = pickle.load ( fileHandle )??
5. fileHandle.close()??
import pickle?
fileHandle = open ( 'pickleFile.txt' )?
testList = pickle.load ( fileHandle )?
fileHandle.close()?
如上所述,使用Python的“pickle”模塊編組確實很簡單。眾多對象可以通過它來存儲到文件中。如果可以的話,“cPickle”同樣勝任這個工作。它和“pickle”模塊一樣,但是速度更快:?
1. import cPickle??
2.???
3. fileHandle = open ( 'pickleFile.txt', 'w' )??
4. cPickle.dump ( 1776, fileHandle )??
5. fileHandle.close()??
import cPickle?
fileHandle = open ( 'pickleFile.txt', 'w' )?
cPickle.dump ( 1776, fileHandle )?
fileHandle.close()?
五、創建“虛擬”文件?
你用到的許多模塊包含需要文件對象作為參數的方法。但是,有時創建并使用一個真實的文件并讓人感到有些麻煩。所幸的是,在Python中,你可以使用“StringIO”模塊來創建文件并將其保存在內存中:?
1. import StringIO??
2.???
3. fileHandle = StringIO.StringIO ( "Let freedom ring" )??
4. print fileHandle.read() # "Let freedom ring."??
5. fileHandle.close()??
import StringIO?
fileHandle = StringIO.StringIO ( "Let freedom ring" )?
print fileHandle.read() # "Let freedom ring."?
fileHandle.close()?
cStringIO”模塊同樣有效。它的使用方法和“StringIO”一樣,但就像“cPickle”之于“pickle”,它速度更快:?
1. import cStringIO??
2.???
3. fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )??
4. print fileHandle.read() # "To Kill a Mockingbid"??
5. fileHandle.close()??
import cStringIO?
fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )?
print fileHandle.read() # "To Kill a Mockingbid"?
fileHandle.close()?
結論?
文件管理,是眾多編程語言的程序員在編寫應用程序是經常遇到的問題。幸好,和其它語言相比,Python使其出乎意料地容易。Python的標準庫中提供了許多相關的模塊幫助程序員解決這方面的問題,而它的面向對象的機制也簡化了操作。?
好了,現在你已經了解了Python中文件管理的基本知識,可以在今后的應用程序中很好地使用了。?
總結
以上是生活随笔為你收集整理的python文件读写2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pythonGB2312乱码问题
- 下一篇: python debug【】