1. os庫基本介紹
os庫提供通用的、基本的操作系統交互功能
- os 庫是Python標准庫,包含幾百個函數
- 常用路徑操作、進程管理、環境參數等幾類
詳解介紹
-
路徑操作:os.path子庫,處理文件路徑及信息
-
進程管理:啟動系統中其他程序
-
環境參數:獲得系統軟硬件信息等環境參數
2. os庫之路徑操作
os庫使用os.path子庫來進行路徑操作,os.path子庫以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)
3. os庫的進程管理
進程管理指的是使用我們編寫的python程序,去調用其他的外部程序。那么os庫提供了—個函數叫system,它夠執行復它的程序或命令。
os.system(command)
- 執行程序或命令command
- 在Windows系統中,返回值為cmd的調用返回信息
例子:使用 os.system 函數調用 Windows 下面的計算器程序
只需要將計算器程序的文件路徑作為參數放到os.system函數中,執行該語句之后,計算器程序運行出來,同時本函數調用結束返回一個0,指的是程序正確運行
>>> import os
>>> os.system("C:\\Windows\\System32\\calc.exe")
0
我們也可以給調用的程序賦予相關的參數,比如調用windows操作系統中的 mspaint ,也就是畫圖程序,並且指定一個文件給這個畫圖程序讓它默認打開。只需要使用畫圖程序 mspaintexe ,同時在后面通過空格給合出要打開的文件,作為參數給出 system函數就可以了。
>>> os.system("C:\\Windows\\System32\\mspaint.exe C:\\Users\\ASUS\\Desktop\\1.PNG")
0
注意要打開的程序和后面的參數之間只有一個空格,沒有其他東西。
4. os庫之環境參數
函數 | 描述 | 例子 |
---|---|---|
os.chdir(path) | 修改當前程序操作的路徑 | >>>os.chdir("D:") |
os.getcwd() | 返回程序的當前路徑 | >>>os.getcwd() |
os.getlogin() | 獲得當前系統登錄用戶名稱 | >>>os.getlogin() |
os.cpu_count() | 獲得當前系統的CPU數量 | >>>os.cpu_count() |
os.urandom(n) | 獲得n個字節長度的隨機字符串,通常用於加解密運算 | >>>os.urandom(10) |