說說Python 中的文件操作 和 目錄操作
我們知道,文件名、目錄名和鏈接名都是用一個字符串作為其標識符的,但是給我們一個標識符,我們該如何確定它所指的到底是常規文件文件名、目錄名還是鏈接名呢?這時,我們可以使用os.path模塊提供的isfile函數、isdir函數和 islink函數來達成我們的目標,如下所示:
print myfile, ’是一個’,
if os.path.isfile(myfile):
print ’plain file’
if os.path.isdir(myfile):
print ’directory’
if os.path.islink(myfile):
print ’link’
您還可以查找文件的日期及其大小:
time_of_last_access = os.path.getatime(myfile)
time_of_last_modification = os.path.getmtime(myfile)
size = os.path.getsize(myfile)
這里的時間以秒為單位,并且從1970年1月1日開始算起。為了獲取以天為單位的最后訪問日期,可以使用下列代碼:
import time # time.time()返回當前時間
age_in_days = (time.time()-time_of_last_access)/(60*60*24)
為了獲取文件的詳細信息,可以使用os.stat函數和stat模塊中的其它實用程序來達到目的,如下:
import stat
myfile_stat = os.stat(myfile)
size = myfile_stat[stat.ST_SIZE]
mode = myfile_stat[stat.ST_MODE]
if stat.S_ISREG(mode):
print ’%(myfile)是一個常規文件,大小為 %(size)d 字節’ %\
vars()
有關stat模塊的詳細信息,請參見Python Library Reference。若想測試一個文件的讀、寫以及執行權限,可以用os.access函數,具體如下所示:
if os.access(myfile, os.W_OK):
print myfile, ’具有寫權限’
if os.access(myfile, os.R_OK | os.W_OK | os.X_OK):
print myfile, ’具有讀、寫以及執行權限’
http://tech.it168.com/a2009/0708/602/000000602694_1.shtml
在很多應用中,文件操作是一個基本的功能,也是很重要的一部分.相對于其他語言來說,python對文件操作非常簡單
讀和寫:
從文本中讀取數據和把數據寫進文本是文本的基本操作.這個非常簡單.我們打開一個文本準備寫數據:
fp = open ( "test.txt", "w" )
"w"表明我們將要把數據寫到文本中.剩下的就比較容易理解.下一步實把數據寫進文本中:
fp.write ( ' This is a test. \nReady, it is. ' )
這就把字符串"This is a test."寫進文本的第一行,"Really , it is."寫到了第二行.最后,我們需要清理和關閉文本.
fp.close( )
正如你所看到的,這個很容易,特別是對python的對象.但要清楚,當你使用"w"模式去再次寫數據到文本中的時候,文本中的所有內容都會背刪除掉.為了解決這個問題,可以使用"a"模式去把數據追加到文本末尾,添加數據到末尾:
fp = open ( ' test.txt ', ' a ' )
fp.write ( ' \n\n\nBottom line. ' )
fp.close ( )
現在我們把文本的數據讀出來并顯示:
fp = open ( ' test.txt ' )
print fp.read ( )
fp.close( )
這把文本中數據全部讀取出來并顯示出來.我們也可以讀取文本中的一行數據:
fp = open ( ' test.txt ' )
print fp.readline ( ) # " This is a test . "
同樣也可以把文本中的所有行存儲到一個list中:
fp = open ( ' test.txt ' )
fileList = fp.readlines( )
for fileline in fileList :
print '>>', fileline
fp.close( )
當在從文本中讀取數據時,Python會記住指針在文本中的位置,如下例子:
fp = open ( ' test.txt ' )
garbage = fp.readline( )
fp.readline ( ) # "Really, it is. "
fp.close ( )
只有第二行顯示出來.當然,我們也可以通過把指針定位到其他地方來讀取數據.
fp = open ( 'test.txt' )
garbage = fp.readline ( )
fp .seek ( 0 )
print fp.readline ( ) # " This is a test . "
fp.close ( )
由上面的例子可以知道,我們可以告訴python繼續從文本的第一個字節開始讀取數據. 因此,第一行數據被打印出來. 我們同樣可以要求python告訴指針當前位置:
fp = open ( ' test.txt ' )
print fp.readlien ( ) # " This is a test "
print fp .tell ( 0 ) # " 17 "
print fp.readline( ) # " Really , it is "
同樣,一次也可以讀取指定字節數的數據:
fp = open ( ' test.txt ' )
print fp ( 1 ) # " T "
fp.seek ( 4 )
print fp.read ( 1 ) # " T "
當我們在Windows 和 Macintosh平臺時,有時候可以需要以二進制的模式來寫數據,比如圖片文件.為了做到這點,只要以"b"模式打開文本:
fp = open ( ' testBinary.txt ', ' wb ' )
fp.write ( ' There is no spoon. ' )
fp.close ( )
fp = open ( ' testBinary.txt ' , ' rb ' )
print fp.read ( )
fp .close ( )