您的位置:首页 > 编程语言 > Python开发

聪哥的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')




程序员实战技能,扫一扫学习
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: