056 模組7-os庫的基本使用
阿新 • • 發佈:2020-12-13
目錄
一、os庫基本介紹
os庫提供通用的、基本的作業系統互動功能
-
os庫是Python標準庫,包含幾百個函式
-
常用路徑操作、程序管理、環境引數等幾類
-
路徑操作:os.path子庫,處理檔案路徑及資訊
-
程序管理:啟動系統中其他程式
-
環境引數:獲得系統軟硬體資訊等環境引數
二、os庫之路徑操作
2.1 路徑操作
os.path子庫以path為入口,用於操作和處理檔案路徑
import os.path
或import os.path as op
函式 | 描述 |
---|---|
os.path.abspath(path) | 返回path在當前系統中的絕對路徑,os.path.abspath("file.txt") # 'C:\\Users\\Tian Song\\Python36-32\\file.txt' |
os.path.normpath(path) | 歸一化path的表示形式,統一用\分隔路徑,os.path.normpath("D://PYE//file.txt") # 'D:\\PYE\\file.txt' |
os.path.relpath(path) | 返回當前程式與檔案之間的相對路徑 (relative path),os.path.relpath("C://PYE//file.txt") # '..\\..\\..\\..\\..\\..\\..\\PYE\\file.txt' |
os.path.dirname(path) | 返回path中的目錄名稱,os.path.dirname("D://PYE//file.txt") # 'D://PYE' |
os.path.basename(path) | 返回path中最後的檔名稱,os.path.basename("D://PYE//file.txt") # 'file.txt' |
os.path.join(path, *paths) | 組合path與paths,返回一個路徑字串,os.path.join("D:/", "PYE/file.txt") # 'D:/PYE/file.txt' |
os.path.exists(path) | 判斷path對應檔案或目錄是否存在,返回True或False,os.path.exists("D://PYE//file.txt") # False |
os.path.isfile(path) | 判斷path所對應是否為已存在的檔案,返回True或False,os.path.isfile("D://PYE//file.txt") # True |
os.path.isdir(path) | 判斷path所對應是否為已存在的目錄,返回True或False,os.path.isdir("D://PYE//file.txt") # False |
os.path.getatime(path) | 返回path對應檔案或目錄上一次的訪問時間,os.path.getatime("D:/PYE/file.txt") # 1518356633.7551725 |
os.path.getmtime(path) | 返回path對應檔案或目錄最近一次的修改時間,os.path.getmtime("D:/PYE/file.txt") # 1518356633.7551725 |
os.path.getctime(path) | 返回path對應檔案或目錄的建立時間,time.ctime(os.path.getctime("D:/PYE/file.txt")) # 'Sun Feb 11 21:43:53 2018' |
os.path.getsize(path) | 返回path對應檔案的大小,以位元組為單位,os.path.getsize("D:/PYE/file.txt") # 180768 |
os.path.abspath(path)
os.path.normpath(path)
os.path.relpath(path)
os.path.dirname(path)
os.path.basename(path)
os.path.join(path)
os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)
os.path.getatime(path)
os.path.getmtime(path)
os.path.getctime(path)
os.path.getsize(path)
三、os庫之程序管理
3.1 程序管理
os.system(command)
- 執行程式或命令command
- 在Windows系統中,返回值為cmd的呼叫返回資訊
import os
os.system("C:\\Windows\\System32\\calc.exe") # 0
四、os庫之環境引數
4.1 環境引數
獲取或改變系統環境資訊
函式 | 描述 |
---|---|
os.chdir(path) | 修改當前程式操作的路徑,os.chdir("D:") |
os.getcwd() | 返回程式的當前路徑,os.getcwd() # 'D:\\' |
os.getlogin() | 獲得當前系統登入使用者名稱稱,os.getlogin() # 'Tian Song' |
os.cpu_count() | 獲得當前系統的CPU數量,os.cpu_count() # 8 |
os.urandom(n) | 獲得n個位元組長度的隨機字串,通常用於加解密運算,os.urandom(10) # b'7\xbe\xf2!\xc1=\x01gL\xb3' |