1. 程式人生 > >Python基礎【os】

Python基礎【os】

os模組

獲取作業系統型別

函式:os.name
以字串形式返回作業系統的型別
'posix':Linux作業系統
'nt':Windows作業系統

獲取計算機資訊

函式:os.uname(linux支援)
windows中匯入platform模組
platform

程式碼:

import platform
info = platform.uname()
print(info)

測試結果:

Python基礎【os】


獲取系統環境變數

函式:os.environ
以environ物件形式返回系統的環境變數

程式碼:

print(os.environ)
print(os.environ.get('PATH'))

測試結果:

Python基礎【os】


os.path

函式:os.path.isabs(path)
判斷path是否是絕對路徑,是返回True,不是返回False
函式:os.path.abspath(filename)
返回檔案的絕對路徑
函式:os.path.join('path','filename')
返回拼接的路徑
函式:os.path.basename(filename)
返回獲取的檔名
函式:os.path.dirname(filename)
返回獲取的目錄名
函式:os.path.splitext('hello.png')
分離檔名和字尾,以字串形式返回分離的檔名和字尾
函式:os.path.split('/tmp/hello/hello.png')
分離目錄名和檔名,以字串形式返回分離的目錄名和檔名
函式:os.path.exists('filename')
判斷檔案是否存在,存在返回True,不存在返回False

程式碼:

print(os.path.isabs('/tmp/passwd3'))
print(os.path.isabs('hello'))

測試結果:

Python基礎【os】


建立目錄/刪除目錄

函式:os.mkdir('dirname')
建立目錄
函式:os.makedirs('/dir/dir1')
遞迴建立目錄
函式:os.rmdir('dirname')
刪除目錄

程式碼:

測試結果:


建立檔案/刪除檔案

函式:os.mknod('filename')
建立檔案
函式:os.remove('filename')
刪除檔案

程式碼:

測試結果:


檔案重新命名

函式:os.rename('filename1','filename2')
修改filename1名為filename2