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

Python编程快速上手 让繁琐工作自动化 第9章 9.5 项目:将一个文件夹备份到一个ZIP文件

2020-07-31 10:49 316 查看

9.5 项目:将一个文件夹备份到一个ZIP文件
书中作者给了代码。我的代码做了一点改动,用f’{}'格式化字符串替代了占位符%s。
另外我发现如果文件夹不是空的,添加文件名到zip文件的那行代码要不要效果都一样,
如果文件夹是空的,文件名就不会被添加到zip文件中,有兴趣的可以试一试。
下面是我的代码:

import os,zipfile
def backup(f):
pt=os.path.abspath(f)
nm=os.path.basename(pt)
n=1
while True:
zp=nm+'.'+str(n)+'.zip'
if not os.path.exists(zp):
break
n=n+1
print(f'Creating backup zip file:{zp}...')
zpo=zipfile.ZipFile(zp,'w')
for a,b,c in os.walk(pt):
zpo.write(a)
for files in c:
if files.startswith(nm+'.') and files.endswith('.zip'):
continue
zpo.write(os.path.join(a,files))
print('finished')
backup('.')                                            #'.'是当前工作目录

类似程序的想法:
查找指定文件夹中文件名含有某些词的文件。比如,查找文件名带有‘test’的文件
下面是代码:

import os,re
reg=re.compile(r'test')
pth=os.path.abspath('.')
l=os.walk(pth)
for a,b,c in l:
for r in c:
if not reg.search(r):
continue
print(f'The file name of "{r}" with "test". It is in folder:{a}')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐