一、os模塊概述
Python os模塊包含普遍的操作系統功能。如果你希望你的程序能夠與平臺無關的話,這個模塊是尤爲重要的。(一語中的)
二、常用方法
1、os.name
輸出字符串指示正在使用的平臺。如果是window 則用'nt'表示,對於Linux/Unix用戶,它是'posix'。
2、os.getcwd()
函數得到當前工作目錄,即當前Python腳本工作的目錄路徑。
3、os.listdir()
返回指定目錄下的所有文件和目錄名。
>>> os.listdir(os.getcwd()) ['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe'] >>>
4、os.remove()
刪除一個文件。
5、os.system()
運行shell命令。
>>> os.system('dir') 0 >>> os.system('cmd') #啓動dos
6、os.sep 可以取代操作系統特定的路徑分割符。
7、os.linesep字符串給出當前平臺使用的行終止符
>>> os.linesep '\r\n' #Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。 >>> os.sep '\\' #Windows >>>
8、os.path.split()
函數返回一個路徑的目錄名和文件名
>>> os.path.split('C:\\Python25\\abc.txt') ('C:\\Python25', 'abc.txt')
9、os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄。
>>> os.path.isdir(os.getcwd()) True >>> os.path.isfile('a.txt') False
10、os.path.exists()函數用來檢驗給出的路徑是否真地存在
>>> os.path.exists('C:\\Python25\\abc.txt') False >>> os.path.exists('C:\\Python25') True >>>
11、os.path.abspath(name):獲得絕對路徑
12、os.path.normpath(path):規範path字符串形式
13、os.path.getsize(name):獲得文件大小,如果name是目錄返回0L
14、os.path.splitext():分離文件名與擴展名
>>> os.path.splitext('a.txt') ('a', '.txt')
15、os.path.join(path,name):連接目錄與文件名或目錄
>>> os.path.join('c:\\Python','a.txt') 'c:\\Python\\a.txt' >>> os.path.join('c:\\Python','f1') 'c:\\Python\\f1' >>>
16、os.path.basename(path):返回文件名
>>> os.path.basename('a.txt') 'a.txt' >>> os.path.basename('c:\\Python\\a.txt') 'a.txt' >>>
17、os.path.dirname(path):返回文件路徑
>>> os.path.dirname('c:\\Python\\a.txt') 'c:\\Python'