Python中常用的os操作彙總
阿新 • • 發佈:2020-11-09
Python自動的os庫是和作業系統互動的庫,常用的操作包括檔案/目錄操作,路徑操作,環境變數操作和執行系統命令等。
檔案/目錄操作
- 獲取當前目錄(pwd):
os.getcwd()
- 切換目錄(cd):
os.chdir('/usr/local/')
- 列出目錄所有檔案(ls):
os.listdir('/usr/local/')
- 建立目錄(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目錄及子下所有檔案和目錄,並組裝出每個檔案完整的路徑名
import os for 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('目錄:',name))
路徑操作
- 當前Python指令碼檔案:
__file__
- 獲取檔案所在路徑:
os.path.basename(__file__)
# 不含當前檔名 - 獲取檔案絕對路徑:
os.path.abspath(__file__)
# 包含當前檔名 - 獲取所在目錄路徑:
os.path.dirname(__file__)
- 分割路徑和檔名:
os.path.split('/usr/local/a.txt')
# 得到一個[路徑,檔名]的列表 - 分割檔名和副檔名:
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')
示例:獲取專案根路徑和報告檔案路徑
假設專案結構如下
project/ data' reports/ report.html testcases/ config.py run.py
在run.py中獲取專案的路徑和report.html的路徑
# filename: run.py import os base_dir = os.path.dirname(__file__) # __file__是run.py檔案,os.path.dirname獲取到其所在的目錄project即專案根路徑 report_file = os.path.join(base_dir,'reports','report.html') # 使用系統路徑分隔符('\')連線專案根目錄base_dir和'reports'及'report.html'得到報告路徑 print(report_file)
環境變數操作
- 獲取環境變數:os.environ.get('PATH')或os.getenv('PATH')
- 設定環境變數:os.environ['MYSQL_PWD']='123456'
執行系統命令
執行系統命令:os.system("jmeter -n -t /usr/local/demo.jmx")
# 無法獲取螢幕輸出的資訊,相要獲取執行螢幕資訊,可以使用subprocess
作者: 韓志超
出處:https://www.cnblogs.com/superhin/p/13880748.html
更多關於python的相關知識,請關注python客棧
以上就是Python中常用的os操作彙總的詳細內容,更多關於python os操作的資料請關注我們其它相關文章!