Python编程快速上手 让繁琐工作自动化 第9章实践项目 9.8.3 消除缺失的编号和附加的挑战
2020-08-04 16:26
555 查看
这个项目网上的答案没有觉得满意的,没有严格按题目要求来,尤其是都没有写附加挑战的答案。
首先项目要求要定位缺失的编号,所以代码要找出哪些编号缺失了,但是网上的那些答案这一步都没做。
另外,附加挑战还没发现有人写代码,没人挑战,那就由我来做吧。第一部分是‘消除缺失的编号’的代码,第二部分是附加挑战的代码。
先看项目要求:
‘’9.8.3 消除缺失的编号:
编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,诸如spam001.txt, spam002.txt等,并定位缺失的编号(例如存在spam001.txt和spam003.txt,但不存在spam002.txt)。让该程序对所有后面的文件改名,消除缺失的编号。
作为附加的挑战,编写另一个程序,在一些连续编号的文件中,空出一些编号,以便加入新的文件。‘’
下面上代码:
1.消除缺失的编号:
import re, os, shutil #定位缺失编码并打印出哪些编号缺失。 reg=re.compile(r'test(\d\d\d)\.py') files=os.listdir('.') fnl=[] #文件名编号列表 fls=[] #文件名列表 for file in files: if reg.search(file): no=reg.search(file).group(1) fnl.append(no) fnl.sort() a=1 print('The lost file numbers are:') for i in range(len(fnl)): b=int(fnl[i]) if b-a: for n in range(a,b): nlst='test'+str(n).rjust(3,'0')+'.py' print(f' "{nlst}"',end=',') a=b+1 print('') #重命名文件。 print('Renaming the files...') for file in files: if reg.search(file): fl=reg.search(file).group() fls.append(fl) fls.sort() for filename in fls: newname='test'+ str(fls.index(filename)+1).rjust(3,'0')+'.py' if filename != newname: shutil.move(filename,newname) print('Done')
2.附加的挑战:
import re, os, shutil #把编号连续的文件名放到一个列表中,然后对列表排序。 lst=[] reg=re.compile(r'test(\d\d\d)\.py') files=os.listdir('.') for file in files: if reg.search(file): filename=reg.search(file).group() lst.append(filename) lst.sort() #确定要空出的文件名范围。 while True: a=input('Please enter the beginning number:') b=input('Please enter the ending number:') if 1<=int(a)<=int(b): print('The numbers range done') break else: print('The number range is illegal. Please enter again!') '''对包含文件名的列表分片,分成两个新列表,然后把第二个新列表中文件名对应的文件 移动到另外一个文件夹并重命名,然后也把第一个新列表中文件名对应的文件移动到那个文件夹''' lst1=lst[0:int(a)-1] lst2=lst[int(a)-1:] for file in lst2: newname='test'+str(int(b)+1+lst2.index(file)).rjust(3,'0')+'.py' shutil.move(file,f'0\\{newname}') for file in lst1: shutil.move(file,'0')
相关文章推荐
- Python编程快速上手 让繁琐工作自动化 | 第三章 :实践项目
- Python 编程快速上手 让繁琐工作自动化-第九章实践项目 9.8.1选择性拷贝
- Python 编程快速上手 让繁琐工作自动化-第八章实践项目
- Python编程快速上手——让繁琐工作自动化 第七章 实践项目
- Python编程快速上手——让繁琐工作自动化第十二章实践题
- 【python】《Python编程快速上手+让繁琐工作自动化》每章实践项目答案(第六章)
- Python编程快速上手——让繁琐工作自动化第九章实践题
- 《Python 编程快速上手 — 让繁琐工作自动化》读书笔记之【第9章 组织文件】
- 【python】《Python编程快速上手+让繁琐工作自动化》每章实践项目答案(第七章)
- Python编程快速上手——让繁琐工作自动化,第三章实践题答案。
- Python编程快速上手——让繁琐工作自动化第八章实践题
- Python编程快速上手——让繁琐工作自动化第三章实践题
- Python编程快速上手——让繁琐工作自动化第六章实践题
- 【python】《Python编程快速上手+让繁琐工作自动化》每章实践项目答案(第五章)
- Python编程快速上手——让繁琐工作自动化第五章实践题
- Python编程快速上手——让繁琐工作自动化第四章实践题
- 【python】《Python编程快速上手+让繁琐工作自动化》每章实践项目答案(三、四章)
- Python编程快速上手——让繁琐工作自动化第七章实践题
- Python编程快速上手——让繁琐工作自动化第十章实践题
- Python 编程快速上手 让繁琐工作自动化 高清pdf