Python 內建模組:os模組

weixin_30639719發表於2020-04-05
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'
 
系轉載,抱歉忘記出處了。

轉載於:https://www.cnblogs.com/ernest-zhang/p/5616866.html

相關文章