聪哥的Python脚本——文件、文件夹操作

来源:互联网 发布:mysql workbench导入 编辑:程序博客网 时间:2024/05/17 22:04
# -*- encoding: utf-8 -*-import osimport shutilimport zipfileimport sysreload(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')



程序员实战技能,扫一扫学习


0 0
原创粉丝点击