最近下载到一套电子书文件,里面有上万本电子书,每本电子书又在不同的子文件夹中,层层嵌套。而我需要的是epub格式的文件,因此,我打算将所有的epub的文件都放到同一个文件夹中。
代码如下:
import os
import shutil
def find_epub(file_path, target, result): # 寻找epub文件
files = os.listdir(file_path) # 找到路径中的所有文件
for f in files:
npath = file_path + '/' + f # 路径+文件名
if os.path.isfile(npath):
if os.path.splitext(npath)[1] == target: # 匹配目标 .epub
result.append(npath)
if os.path.isdir(npath):
if f[0] == '.':
pass
else:
find_epub(npath, target, result)
return result
def copy_file(result): # 复制epub文件
file_path2 = r"F:\books_epub" # 复制到路径
for file in result:
print(str(file).split("/")[-1]) # 书名
file2 = file_path2 + "/" + str(file).split("/")[-1] # 路径+书名
shutil.copy(file, file2) # 复制文件
if __name__ == "__main__":
file_path = r"F:\books"
result = []
find_epub(file_path, ".epub", result)
copy_file(result)
结果如下:
完美解决!