Python os庫常用操作代碼匯總
Python自動(dòng)的os庫是和操作系統(tǒng)交互的庫,常用的操作包括文件/目錄操作,路徑操作,環(huán)境變量操作和執(zhí)行系統(tǒng)命令等。
文件/目錄操作
獲取當(dāng)前目錄(pwd): os.getcwd() 切換目錄(cd): os.chdir(’/usr/local/’) 列出目錄所有文件(ls):os.listdir(’/usr/local/’) 創(chuàng)建目錄(mkdir):os.makedirs(’/usr/local/tmp’) 刪除目錄(rmdir):os.removedirs(’/usr/local/tmp’) # 只能刪除空目錄,遞歸刪除可以使用import shutil;shutil.rmtree(’/usr/local/tmp’) 刪除文件(rm):os.remove(’/usr/local/a.txt’) 遞歸遍歷目錄及子目錄:os.walk()示例:遍歷/usr/local目錄及子下所有文件和目錄,并組裝出每個(gè)文件完整的路徑名
import osfor root, dirs, files in os.walk('/usr/local', topdown=False): for name in files: print(’文件:’, os.path.join(root, name)) for name in dirs: print(’目錄:’, os.path.join(root, name))
路徑操作
當(dāng)前Python腳本文件:__file__ 獲取文件所在路徑:os.path.basename(__file__) # 不含當(dāng)前文件名 獲取文件絕對(duì)路徑:os.path.abspath(__file__) # 包含當(dāng)前文件名 獲取所在目錄路徑:os.path.dirname(__file__) 分割路徑和文件名:`os.path.split(’/usr/local/a.txt’) # 得到一個(gè)[路徑,文件名]的列表 分割文件名和擴(kuò)展名:os.path.splitext(’a.txt’) # 得到[’a’, ’.txt’] 判斷路徑是否存在:os.path.exists(’/usr/local/a.txt’) 判斷路徑是否文件:os.path.isfile(’/usr/local/a.txt’) 判斷路徑是否目錄:os.path.isdir(’/usr/local/a.txt’) 組裝路徑:os.path.join(’/usr’, ’local’, ’a.txt’)示例:獲取項(xiàng)目根路徑和報(bào)告文件路徑
假設(shè)項(xiàng)目結(jié)構(gòu)如下
project/data’reports/report.htmltestcases/config.pyrun.py
在run.py中獲取項(xiàng)目的路徑和report.html的路徑
# filename: run.pyimport osbase_dir = os.path.dirname(__file__) # __file__是run.py文件,os.path.dirname獲取到其所在的目錄project即項(xiàng)目根路徑report_file = os.path.join(base_dir, ’reports’, ’report.html’) # 使用系統(tǒng)路徑分隔符(’’)連接項(xiàng)目根目錄base_dir和’reports’及’report.html’得到報(bào)告路徑print(report_file)
環(huán)境變量操作
獲取環(huán)境變量:os.environ.get(’PATH’)或os.getenv(’PATH’) 設(shè)置環(huán)境變量:os.environ[’MYSQL_PWD’]=’123456’執(zhí)行系統(tǒng)命令
執(zhí)行系統(tǒng)命令:os.system('jmeter -n -t /usr/local/demo.jmx') # 無法獲取屏幕輸出的信息,相要獲取運(yùn)行屏幕信息,可以使用subprocess
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML入門的常見問題(一)2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. PHP字符串前后字符或空格刪除方法介紹4. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄5. jsp實(shí)現(xiàn)登錄界面6. css進(jìn)階學(xué)習(xí) 選擇符7. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法8. 解析原生JS getComputedStyle9. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖10. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程
