python3_06_01.模組之os
- 2020 年 1 月 6 日
- 筆記
好車配好輪。
os.environ |
獲取系統環境變數 |
|
---|---|---|
os.name |
字元串指示當前使用平台。win->'nt'; Linux->'posix' |
|
os.sep |
作業系統特定的路徑分隔符,win下為"\",Linux下為"/" |
>>> os.getcwd() + os.sep + 'world.txt' |
'/tmp/world.txt' 目錄字元串拼接很有用 |
||
os.linesep |
當前平台使用的行終止符,win下為"tn",Linux下為"n" |
|
os.system('top') |
運行shell命令,直接顯示 |
|
os.getcwd() |
查看當前目錄 |
|
切換目錄 |
|
|
os.listdir() |
列出目錄下所有內容 |
|
os.mkdir('test') |
新建單級目錄test |
|
os.rmdir('test') |
刪除目錄test,目錄不為空則報錯 |
|
os.removedirs('ceshi/test') |
遞歸刪除目錄,ceshi也會被刪除,不為空報錯 |
|
os.makedirs('ceshi/test') |
新建多層遞歸目錄 |
|
os.remove('test.txt') |
刪除文件 |
|
os.rename('hello.txt','world.txt') |
重命名文件/目錄,前為舊後為新 |
|
os.stat('/tmp/world.txt') |
獲取文件目錄資訊 |
|
os.access('/tmp/world.txt',os.F_OK) |
os.access(path, mode);檢測許可權 |
os.F_OK: 作為access()的mode參數,測試path是否存在。 |
os.R_OK: 包含在access()的mode參數中 , 測試path是否可讀。 |
||
os.W_OK 包含在access()的mode參數中 , 測試path是否可寫。 |
||
os.X_OK 包含在access()的mode參數中 ,測試path是否可執行。 |
||
os.chmod() |
用於更改文件或目錄的許可權。 |
http://www.runoob.com/python/os-chmod.html |
os.chown(path, uid, gid); |
用於更改文件所有者,如果不修改可以設置為 -1 |
|
os.chroot() |
更改當前進程的根目錄為指定的目錄,使用該函數需要管理員許可權。 |
|
os.path.abspath("world.txt") |
返回絕對路徑 |
返回結果: '/tmp/world.txt' |
os.path.basename("/tmp/world.txt") |
返迴文件名 |
返回結果: 'world.txt' |
os.path.isabs("world.txt") |
如果是絕對路徑,返回True |
返回結果: False |
os.path.isdir("/usr") |
如果path是一個存在的目錄,則返回True。否則返回False |
返回結果: True |
os.path.isfile("world.txt") |
如果path是一個存在的文件,返回True。否則返回False |
返回結果: True |
os.path.split("/var/log/messages") |
把路徑分割為文件名 和 目錄名 |
返回結果 : ('/var/log', 'messages') |
os.path.dirname("/var/log/messages") |
獲取文件的上級目錄 |
返回結果: '/var/log' |
os.path.join(path1[, path2[, …]]) |
將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略,這個必會,日後用途非常廣泛! |
請看下面實例 |
#linux下查找文件def find_file(name,start='/'):for relpath,dirs,files in os.walk(start): if name in files: full_path = os.path.join(start,relpath,name) file_path = os.path.normpath(os.path.abspath(full_path)) return file_path |