本文实例为大家分享了pyhton操作文件的具体代码,供大家参考,具体内容如下
copy_file
功能:将某个文件夹下的所有文件(文件夹)复制到另一个文件夹
#! python 3 # -*- coding:utf-8 -*- # Autor: GrayMac import shutil import os basefileclass = '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)
zip_file
功能:将某个文件夹下面的所有文件(文件夹)压缩
#! python 3 # -*- coding:utf-8 -*- # Autor: GrayMac import zipfile import os #dirpath:压缩源文件路径 outpath:输出文件夹路径 outname:输出压缩文件名 basefilepath = 'basefile/' def zip_file(dirpath,outpath,outname): print('Start ZIP ' + dirpath + ' To ' + outname) zip = zipfile.ZipFile(outpath + outname,"w",zipfile.ZIP_DEFLATED) for path,dirnames,filenames in os.walk(dirpath): # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩 fpath = path.replace(dirpath,basefilepath) for filename in filenames: zip.write(os.path.join(path,filename),os.path.join(fpath,filename)) zip.close() print('ZIP' + outname + 'successed !') zip_file(dirpath,outpath,outname)
del_file
功能:将某个文件夹下面的所有文件(文件夹)删除
#! python 3 # -*- coding:utf-8 -*- # Autor: GrayMac import shutil import os #path_data 删除文件夹路径 #os.listdir(path_data) 返回一个列表,里面是当前目录下面的所有东西的相对路径 #os.path.isfile(file_data) 判断是否为文件 #os.remove(file_data) 删除文件 #shutil.rmtree(file_data) 删除文件夹(非空) def del_file(path_data): print('Start Delete : ' + path_data) for filenames in os.listdir(path_data) : file_data = path_data + "\\" + filenames#当前文件夹的下面的所有东西的绝对路径 if os.path.isfile(file_data) : os.remove(file_data) else: shutil.rmtree(file_data) print('Delete successed !')
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- Merryland《Merryland》[320K/MP3][69.48MB]
- 苏芮.1991-停在我心里的温柔【福茂】【WAV+CUE】
- 苏慧伦.2020-面面Every.Side.of.Me【相信音乐】【WAV+CUE】
- 群星.1991-不一样的感觉REMIX【宝丽金】【WAV+CUE】
- 银霞.1983-《你那好冷的小手》珍藏纪念版[WAV分轨]
- 银霞.2002-《国语巨星专辑VOL.3》2CD台湾版[WAV+CUE]
- 金池刘罡《昨日情歌HQ》头版限量编号[低速原抓WAV+CUE]
- 段奥娟.2024-23·岁碎念【白米范】【FLAC分轨】
- 顺子.2001-昨日·唯一·更多·顺子自选辑【魔岩】【WAV+CUE】
- 无印良品.1999-私藏三首·原创相对论(EP)【滚石】【WAV+CUE】
- Merryland《Merryland》[FLAC/分轨][170.22MB]
- 庄锭欣 ELKIE《没有你的未来》[320K/MP3][15.78MB]
- 庄锭欣 ELKIE《没有你的未来》[FLAC/分轨][36MB]
- TchaikovskySwanLake,Op.20柴可夫斯基天鹅湖(2013)SACD[Hi-Res]
- 24bit达人艺典《琴歌终极版》整轨WAV+CUE