《python编程快速上手》第9章 作业9.8.3

本来想偷懒不做这题,感觉好麻烦,就上网找找答案。
结果没有满意的,还是自己写一个吧。
相较于一位网上同学的答案,此代码亮点在’%03d’和zip()函数的使用,还有任务拆分清晰。
做了个把小时的,代码还算满意,就作为第一篇博客,激励下自己继续努力。
如有错误,请指出以相互学习,多谢!

#! python3
# complete the filename that contain sequence like’spam001’,’spam003’
# folder named ‘spam’ which contains files [‘abc001.txt’, ‘abc003.txt’, ‘abc004.txt’, ‘abc006.txt’, ‘abc007.txt’, ‘abcabc.txt’]

import os, re, shutil
os.chdir('spam')
# 找到指定文件夹中所有带指定前缀的文件
# look for the particular word in filename
o_filenames = [x for x in os.listdir('.') if '.' in x and x.startswith('abc')]
print(o_filenames)

# 定位缺失的编号
# locate the missing num
numRegex = re.compile(r'^abc(.*?).txt$')
o_num_list = []
for o_filename in o_filenames:
    t_name_re = numRegex.search(o_filename)
    o_num_list.append(t_name_re.group(1))
print(o_num_list)

n_num_list = []
for i in range(1,len(o_num_list)+1):
    t_i = '%03d' % i
    n_num_list.append(t_i)
print(n_num_list)

for i in n_num_list:
    if i not in o_num_list:
        print("abc%s.txt" % i)

# 对文件改名以消除缺失的编号
# rename all files to complete the sequence
for i,v in zip(o_num_list, n_num_list):
    shutil.move('abc%s.txt'%i, 'abc%s.txt'%v)

print('Rename project is done!')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值