1. 程式人生 > >[python] os.getcwd及os.path模組

[python] os.getcwd及os.path模組

一、os.getcwd()

該函式不需要傳遞引數,它返回當前的目錄。需要說明的是,當前目錄並不是指指令碼所在的目錄,而是所執行指令碼的目錄。例如,在PythonWin中輸入如下指令碼。

  1. >>> import os  
  2. >>> print 'current directory is ',os.getcwd()  
  3. current directory is D:\Python25\Lib\site-packages\pythonwin  

這裡是PythonWin的安裝目錄如果將上述內容寫入pwd.py,假設pwd.py位於E:\book\code目錄,執行Windows的命令列視窗,進入E:\book目錄,輸入code\pwd.py,輸出如下所示。

  1. E:\book>code\pwd.py  
  2. current directory is E:\book  

獲得目錄中的內容

在Python中可以使用os.listdir()函式獲得指定目錄中的內容。其原型如下所示。

  1. os.listdir(path) 

其引數含義如下。· path 要獲得內容目錄的路徑。以下例項獲得當前目錄的內容。

  1. >>> import os  
  2. >>> os.listdir(os.getcwd())   

獲得當前目錄中的內容

  1. ['dde.pyd', 'license.txt', 'Pythonwin.exe',  'scintilla.dll', 'win32ui.pyd', 'win32uiole. pyd', 'pywin'] 

  二、os.path模組常用函式簡介

1>basename()   #去掉目錄路徑,返回檔名
 >>>os.path.basename("/root/python/zip.py")
'zip.py'
2>dirname()    #去掉檔名,返回目錄路徑
>>> os.path.dirname("/root/python/zip.py")
'/root/python'
3>join()       #將分離的各部分組合成一個路徑名
>>> os.path.join("/root/python/","zip.py")     
'/root/python/zip.py'
4>
split()      #返回目錄路徑和檔名的元組

>>> os.path.split("/root/python/zip.py")       
('/root/python', 'zip.py')
5>splitdrive() #返回驅動符號和路徑字元元組
>>> os.path.splitdrive("/root/python/zip.py")
('', '/root/python/zip.py')
6>splitext()   #返回檔名和副檔名元組
>>>os.path.splitext("zip.py")
('zip','.py')
7>getatime()   #返回檔案最近的訪問時間
>>> os.path.getatime("/root/python/zip.py")
1297653596
>>> time.ctime(1297653596)
'Mon Feb 14 11:19:56 2011'
8>getctime()   #返回檔案的建立時間
9>getmtime()   #返回檔案的修改時間
10>getsize()   #返回檔案的大小單位為位元組

>>> os.path.getsize("zip.py")
864
11>exists()    #指定路徑(檔案或目錄)是否存在
>>> os.path.exists("/root/python/xukai.py")
False
>>> os.path.exists("/root/python/zip.py") 
True
12>isabs()     #指定路徑是否為絕對路徑
>>> os.path.isabs("/root/python/zip.py")
True
>>> os.path.isabs("root/python/zip.py")
False
13>isdir()     #指定路徑是否存在且為一個目錄
14>isfile()    #指定的路徑是否為一個檔案
15>samefile()  #兩個路徑名是否指向同一個檔案