python 操作檔案一些執行個體總結

來源:互聯網
上載者:User

python中對檔案、檔案夾(檔案操作函數)的操作需要涉及到os模組和shutil模組。

操作前需要 import os;

返回目前的目錄,不包括檔案名稱: os.getcwd();

返回指定目錄下的所有檔案和目錄名:os.listdir("dirname");

os.mknod("test.txt") 建立空檔案,未測試成功,報錯OSError: [Errno 1] Operation not permitted,還沒有查原因,用另一個方法來實現os.system("touch test.txt");

函數用來刪除一個檔案:os.remove();

刪除多個目錄:os.removedirs(r“c:python”)

檢驗給出的路徑是否是一個檔案:os.path.isfile()

檢驗給出的路徑是否是一個目錄:os.path.isdir()

判斷是否是絕對路徑:os.path.isabs()

檢驗給出的路徑是否真地存:os.path.exists();

返回一個路徑的目錄名和檔案名稱:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt')

分離副檔名:os.path.splitext()

擷取路徑名:os.path.dirname()

擷取檔案名稱:os.path.basename()

運行shell命令: os.system()

讀取和設定環境變數:os.getenv() 與os.putenv()

給出當前平台使用的行終止符:os.linesep Windows使用'rn',Linux使用'n'而Mac使用'r'

指示你正在使用的平台:os.name 對於Windows,它是'nt',而對於Linux/Unix使用者,它是'posix'

重新命名:os.rename(old, new)

建立多級目錄:os.makedirs(r“c:pythontest”)

建立單個目錄:os.mkdir(“test”)

擷取檔案屬性:os.stat(file)

修改檔案許可權與時間戳記:os.chmod(file)

終止當前進程:os.exit()

擷取檔案大小:os.path.getsize(filename)


檔案操作:
fp = open("test.txt",w) 直接開啟一個檔案,如果檔案不存在則建立檔案

關於open 模式:

w 以寫方式開啟(清空原內容),
a 以追加模式開啟 (從 EOF 開始, 必要時建立新檔案)
r+ 以讀寫入模式開啟
w+ 以讀寫入模式開啟 (參見 w )
a+ 以讀寫入模式開啟 (參見 a )
rb 以二進位讀模式開啟
wb 以二進位寫入模式開啟 (參見 w )
ab 以二進位追加模式開啟 (參見 a )
rb+ 以二進位讀寫入模式開啟 (參見 r+ )
wb+ 以二進位讀寫入模式開啟 (參見 w+ )
ab+ 以二進位讀寫入模式開啟 (參見 a+ )

 

fp.read([size]) #size為讀取的長度,以byte為單位

fp.readline([size]) #讀一行,如果定義了size,有可能返回的只是一行的一部分

fp.readlines([size]) #把檔案每一行作為一個list的一個成員,並返回這個list。其實它的內部是通過迴圈調用readline()來實現的。如果提供size參數,size是表示讀取內容的總長,也就是說可能唯讀到檔案的一部分。

fp.write(str) #把str寫到檔案中,write()並不會在str後加上一個分行符號

fp.writelines(seq) #把seq的內容全部寫到檔案中(多行一次性寫入)。這個函數也只是忠實地寫入,不會在每行後面加上任何東西。

fp.close() #關閉檔案。python會在一個檔案不用後自動關閉檔案,不過這一功能沒有保證,最好還是養成自己關閉的習慣。 如果一個檔案在關閉後還對其進行操作會產生ValueError

fp.flush() #把緩衝區的內容寫入硬碟

fp.fileno() #返回一個長整型的”檔案標籤“

fp.isatty() #檔案是否是一個終端裝置檔案(unix系統中的)

fp.tell() #返迴文件操作標記的當前位置,以檔案的開頭為原點

fp.next() #返回下一行,並將檔案操作標記位移到下一行。把一個file用於for … in file這樣的語句時,就是調用next()函數來實現遍曆的。

fp.seek(offset[,whence]) #將檔案打操作標記移到offset的位置。這個offset一般是相對於檔案的開頭來計算的,一般為正數。但如果提供了whence參數就不一定了,whence可以為0表示從頭開始計算,1表示以當前位置為原點計算。2表示以檔案末尾為原點進行計算。需要注意,如果檔案以a或a+的模式開啟,每次進行寫操作時,檔案操作標記會自動返回到檔案末尾。

fp.truncate([size]) #把檔案裁成規定的大小,預設的是裁到當前檔案操作標記的位置。如果size比檔案的大小還要大,依據系統的不同可能是不改變檔案,也可能是用0把檔案補到相應的大小,也可能是以一些隨機的內容加上去。

 

目錄操作:
os.mkdir("file") 建立目錄
複製檔案:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是檔案
shutil.copy("oldfile","newfile") oldfile只能是檔案夾,newfile可以是檔案,也可以是目標目錄
複製檔案夾:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目錄,且newdir必須不存在
重新命名檔案(目錄)
os.rename("oldname","newname") 檔案或目錄都是使用這條命令
移動檔案(目錄)
shutil.move("oldpos","newpos")
刪除檔案
os.remove("file")
刪除目錄
os.rmdir("dir")只能刪除空目錄
shutil.rmtree("dir") 空目錄、有內容的目錄都可以刪
轉換目錄
os.chdir("path") 換路徑



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 ( 'nnBottom line.' ) 
3. fileHandle.close() 

fileHandle = open ( 'test.txt', 'a' )
fileHandle.write ( 'nnBottom 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”模組支援Regex:

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.'

使用一定範圍的字元來匹配同樣可行,就像在Regex中使用一樣。假設你想要顯示副檔名前只有一位元字的檔案的檔案名稱:

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()

聯繫我們

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