聪哥的Python脚本——文件、文件夹操作
2016-11-02 22:55
477 查看
# -*- encoding: utf-8 -*- import os import shutil import zipfile import sys reload(sys) sys.setdefaultencoding('utf-8') #获取dir中的所有文件名称 def get_file_list(dir): dir = str(dir) if dir=="": print 'dir is empty!' return [] dir = dir.replace( "/","\\") if dir[ -1] != "\\": dir = dir+"\\" a = os.listdir(dir) b = [x for x in a if os.path.isfile( dir + x ) ] return b #获取文件夹中的文件 def get_file_dir(dir): dir = str(dir) if dir=="": print 'dir is empty!' return () dir = dir.replace( "/","\\") if dir[ -1] != "\\": dir = dir+"\\" a = os.listdir(dir) b = [x for x in a if os.path.isfile( dir + x ) ] d = [x for x in a if os.path.isdir( dir + x ) ] return (b,d) #删除子目录 def remove_sub_dir(dir): for f in os.listdir(dir): if os.path.isdir(dir + "\\" + unicode(f,'GBK')): shutil.rmtree(dir + "\\" + unicode(f,'GBK'),True) #删除文件 def remove_sub_file(dir,ext): for f in get_file_list(dir): file_full_name = unicode(f , "GBK") print file_full_name if file_full_name.endswith(ext): os.remove(dir + '\\' + file_full_name) #压缩文件 def _zip_dir(dirname,zipfilename): filelist = [] if os.path.isfile(dirname): filelist.append(dirname) else : for root, dirs, files in os.walk(dirname): for name in files: filelist.append(os.path.join(root, name)) zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED) for tar in filelist: arcname = tar[len(dirname):] zf.write(tar,arcname) zf.close() #压缩文件夹下的文件夹 def zip_dir(dir,rmdir = False): files = get_file_list(dir) for f in os.listdir(dir): if os.path.isdir(dir + "\\" + unicode(f,'GBK')): zipdir = dir + "\\" + unicode(f,'GBK') zipfilename = zipdir + '.zip' _zip_dir(zipdir,zipfilename) if rmdir: remove_sub_dir(dir) #创建文件夹,并拷贝二维码图片文件到文件夹中 def create_dir_with_qrcode(dir): qrcode_dir = "D:\_Pdf\_qrcode" #二维码图片位置 qrcode_jpg_name = unicode(get_file_list(qrcode_dir)[0] , "GBK") files = get_file_list(dir) for f in files: file_full_name = unicode(f , "GBK") dir_name = unicode(os.path.splitext(f)[0],'GBK') os.makedirs(dir + '\\' + dir_name) shutil.copy(dir + '\\' + file_full_name , dir + '\\' + dir_name + '\\' + file_full_name) shutil.copy(qrcode_dir + '\\' + qrcode_jpg_name , dir + '\\' + dir_name + '\\' + qrcode_jpg_name) pass #压缩pdf文件 def my_zip_pdfs(dir,rmdir = True): #非pdf的文件夹删除 remove_sub_dir(dir) #创建文件夹 create_dir_with_qrcode(dir) #压缩文件,并删除文件夹 zip_dir(dir,True) # 运行脚本 dir="D:\_Pdf\_net" my_zip_pdfs(dir) #删除所有zip文件 # remove_sub_file(dir,'.zip')
程序员实战技能,扫一扫学习
相关文章推荐
- Monkeyrunner 写脚本的技巧(shell 命令,文件操作)---关键点,python创建以时间命名的文件夹
- python3 文件和文件夹操作
- Python文件夹与文件的操作
- python-文件及文件夹操作
- python中对文件、文件夹的操作
- Python文件夹与文件的操作
- python对文件及文件夹的一些操作
- 解压文件夹中的压缩文件 Python脚本
- python文件夹和文件操作
- python写的批量操作远程主机脚本(命令执行,上传、下载文件)
- Python文件夹与文件的操作
- python写的批量操作远程主机脚本(命令执行,上传、下载文件)
- python3.2对文件和文件夹操作
- Python对文件及文件夹的一些操作
- python对文件及文件夹的操作
- 保存指定文件夹下的目录和文件名到文件中 Python 脚本
- python中对文件、文件夹的操作
- 利用python fabric模块写的批量操作远程主机脚本(命令执行,上传、下载文件)
- python中对文件、文件夹的操作
- Python文件及文件夹的一些操作