Python中常用的os操作匯總
Python自動(dòng)的os庫(kù)是和操作系統(tǒng)交互的庫(kù),常用的操作包括文件/目錄操作,路徑操作,環(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.html testcases/ config.py run.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
作者: 韓志超
出處:https://www.cnblogs.com/superhin/p/13880748.html
更多關(guān)于python的相關(guān)知識(shí),請(qǐng)關(guān)注python客棧
以上就是Python中常用的os操作匯總的詳細(xì)內(nèi)容,更多關(guān)于python os操作的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ajax請(qǐng)求添加自定義header參數(shù)代碼2. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟3. 基于javascript處理二進(jìn)制圖片流過程詳解4. 教你如何寫出可維護(hù)的JS代碼5. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……6. Django-migrate報(bào)錯(cuò)問題解決方案7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)9. idea刪除項(xiàng)目的操作方法10. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
