經常使用內置模塊_os

os用於執行操做系統命令函數

 

經常使用的方法:spa

os.getcwd() #獲取當前路徑
os.system('ifconfig')# 執行操做系統命令;只執行命令,可是拿不到命令結果
os.popen('ifconfig').read() #能夠拿到所執行命令結果
os.path.dirname(r'E:\case\login\a.mp3') #獲取a.mps的父目錄
os.path.abspath(__file__) #根據相對路徑獲取絕對路徑,__file__是獲取當前文件絕對路徑
os.path.getsize('a.mp3') #獲取大小
os.path.exists() #判斷文件夾是否存在
os.path.getatime() #獲取文件的最近一次訪問時間
os.path.getctime() #獲取文件的建立時間
os.path.getmtime() #獲取文件的修改時間
print(os.path.split(r'E:\case\login\a.mp3')) #把文件路徑和文件名分開
os.removedirs() #刪空文件夾
os.rmdir() #只能刪除空文件夾
os.remove()  #移除
os.rename() #重命名
os.mkdir('case') #建立單層目錄文件夾
os.makedirs('case/login') #建立多層目錄文件夾
os.listdir(r'e:/home/xx/xxx') #獲取某一個目錄下文件

  os.path.isdir()  #判斷是否是目錄
  os.path.isfile()  #判斷是否是文件操作系統

os.walk()  #遍歷一個目錄內各個子目錄和子文件

os.walk()code

for cur_dir,dirs,files in os.walk('E:\home\day'):    print(cur_dir,dirs,files)     #    print('==============')name = '.mp3'for cur_dir,dirs,files in os.walk('E:\home\day'):    for file in files:        if name in file:            abs_path = os.path.join(cur_dir,file) #找到的文件的絕對路徑            print('找到%s文件,路徑是%s'%(file,abs_path))寫成一個找路徑的函數def search_file(path,name):    for cur_dir, dirs, files in os.walk(path):        for file in files:            if name in file:                abs_path = os.path.join(cur_dir, file)  # 拼接路徑,找到的文件的絕對路徑                print('找到%s文件,路徑是%s' % (file, abs_path))search_file('/home','.mp3') #查找home目錄下全部.mP3的文件
相關文章
相關標籤/搜索