国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python中操作文件的模塊的方法總結

瀏覽:44日期:2022-06-28 13:38:41

在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中操作文件的模塊有幾種內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 策勒县| 京山县| 清丰县| 八宿县| 南雄市| 淮北市| 邢台市| 格尔木市| 华阴市| 凤阳县| 平南县| 宜良县| 沁水县| 红桥区| 历史| 娄烦县| 玉山县| 西昌市| 喀喇| 武平县| 鞍山市| 扎赉特旗| 大新县| 托克托县| 遂溪县| 云林县| 教育| 溧阳市| 弥渡县| 新沂市| 江阴市| 姚安县| 吴堡县| 奉化市| 盐山县| 百色市| 专栏| 濮阳市| 黔西| 泸水县| 南召县|