python中操作文件的模塊的方法總結
在python中操作文件算是一個基本操作,但是選對了模塊會讓我們的效率大大提升。本篇整理了兩種模塊的常用方法,分別是os模塊和shutil模塊。相信這兩種模塊大家在之間的學習中有所涉及,那么關于具體的文件操作部分,我們一起往下看看都有哪些方法和實例吧。
本教程操作環境:windows7系統、Python3版、Dell G3電腦。
Python對文件操作采用的統一步驟是:打開—操作—關閉。
一、python中對文件、文件夾操作時經常用到的os模塊和shutil模塊常用方法1.得到當前工作目錄,即當前Python腳本工作的目錄路徑: os.getcwd()
2.返回指定目錄下的所有文件和目錄名:os.listdir()
3.函數用來刪除一個文件:os.remove()
4.刪除多個目錄:os.removedirs(r'c:python')
5.檢驗給出的路徑是否是一個文件:os.path.isfile()
6.檢驗給出的路徑是否是一個目錄:os.path.isdir()
7.判斷是否是絕對路徑:os.path.isabs()
8.檢驗給出的路徑是否真地存:os.path.exists()
9.返回一個路徑的目錄名和文件名:os.path.split()
二、文件綜合操作實例將文件夾下所有圖片名稱加上’_fc’
# -*- coding:utf-8 -*-import reimport osimport time#str.split(string)分割字符串#’連接符’.join(list) 將列表組成字符串def change_name(path):global iif not os.path.isdir(path) and not os.path.isfile(path):return Falseif os.path.isfile(path):file_path = os.path.split(path) #分割出目錄與文件lists = file_path[1].split(’.’) #分割出文件與文件擴展名file_ext = lists[-1] #取出后綴名(列表切片操作)img_ext = [’bmp’,’jpeg’,’gif’,’psd’,’png’,’jpg’]if file_ext in img_ext:os.rename(path,file_path[0]+’/’+lists[0]+’_fc.’+file_ext)i+=1 #注意這里的i是一個陷阱#或者#img_ext = ’bmp|jpeg|gif|psd|png|jpg’#if file_ext in img_ext:# print(’ok---’+file_ext)elif os.path.isdir(path):for x in os.listdir(path):change_name(os.path.join(path,x)) #os.path.join()在路徑處理上很有用img_dir = ’D:xxxximages’img_dir = img_dir.replace(’’,’/’)start = time.time()i = 0change_name(img_dir)c = time.time() - startprint(’程序運行耗時:%0.2f’%(c))print(’總共處理了 %s 張圖片’%(i))
實例擴展:
#! python 3# -*- coding:utf-8 -*-# Autor: GrayMacimport shutilimport osbasefileclass = ’basefile’#sourcefile:源文件路徑 fileclass:源文件夾 destinationfile:目標文件夾路徑def copy_file(sourcefile,fileclass,destinationfile): #遍歷目錄和子目錄 for filenames in os.listdir(sourcefile): #取得文件或文件名的絕對路徑 filepath = os.path.join(sourcefile,filenames) #判斷是否為文件夾 if os.path.isdir(filepath): if fileclass == basefileclass : copy_file(filepath,fileclass + ’/’ + filenames,destinationfile + ’/’ + filenames) else : copy_file(filepath,fileclass,destinationfile + ’/’ + filenames) #判斷是否為文件 elif os.path.isfile(filepath): print(’Copy %s’% filepath +’ To ’ + destinationfile) #如果無文件夾則重新創建 if not os.path.exists(destinationfile): os.makedirs(destinationfile) shutil.copy(filepath,destinationfile) copy_file(sourcefile,basefileclass,destinationfile)
到此這篇關于python中操作文件的模塊的方法總結的文章就介紹到這了,更多相關python中操作文件的模塊有幾種內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP中常用的22個FSO文件操作函數整理3. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析4. SharePoint Server 2019新特性介紹5. .Net core 的熱插拔機制的深入探索及卸載問題求救指南6. 解決ASP中http狀態跳轉返回錯誤頁的問題7. 讀大數據量的XML文件的讀取問題8. ASP編碼必備的8條原則9. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁10. ASP調用WebService轉化成JSON數據,附json.min.asp