python编程快速上手 第9章实践项目答案
9.8.1 选择性拷贝
import os, shutil
path = "H:\\test1"
new_path = "H:\\test2"
for folderName, subfolders, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(".pdf") or filename.endswith(".jpg"):
old_path = os.path.join(folderName, filename)
print(old_path)
shutil.copy(old_path, new_path)
9.8.2 删除不需要的文件
import os, send2trash
path = "H:\\test1"
for folderName, subfolders, filenames in os.walk(path):
for filename in filenames:
if os.path.getsize(os.path.join(folderName, filename)) >= 100*2**20:
print(os.path.join(folderName, filename))
#send2trash.send2trash(os.path.join(folderName, filename))
9.8.3 消除缺失的编号
import os, re, shutil
path = "H:\\test1"
for filename in os.listdir(path):
if filename.endswith(".txt"):
regex_obj = re.compile(r"spam\d{3}\.txt$")
spam_Filenames = regex_obj.findall(filename)
if filename in spam_Filenames:
pass
else:
number = 1
while True:
new_name = "spam%03d.txt" % number
if not os.path.exists(os.path.join(path, new_name)):
break
number += 1
shutil.move(os.path.join(path, filename), os.path.join(path, new_name))
print("Done.")
附加挑战没看懂,搞不明白题目的要求,再就是被相对路径坑了,以后全部用绝对路径。