玖叶教程网

前端编程开发入门

学习笔记《Python编程快速上手》实践 9.8.1 选择性拷贝

9.8.1 选择性拷贝

编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg).不论这些文件的位置在哪里,将它们拷贝到一个新的文件夹中.

实践分析:

1.需要确认目标文件夹是否存在,如不存在新建。

2.目标目录与工作目录是否为同一个,正常应该不会出现这个情况。但是还是需要用户确认,说不定想把子目录的文件全搬过来。

3.如果目标目录是当前目录的子目录,扫描的时候也会把他扫描进去。加个判断,是的话直接跳过。

4.不知道有没有专用的扩展名获取函数。想到了几个办法:

A.用 file.endswitch("txt") ,太麻烦需要把所有的后缀都写一遍.直接放弃

B.用 file[-4:] in ext 来判断,但是后缀名有长有短,比如 .py 和 .ipynb 也放弃

C.最后用了 file.splite(".")[-1] 来获取最后一个dotall后面的文字。

5.在目标目录中是否存在同名文件,加入到repeat_files列表。


代码如下:

# 9.8.1 选择性拷贝
# 编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg).
# 不论这些文件的位置在哪里,将它们拷贝到一个新的文件夹中.
import os
import shutil
repeat_files = []
copyed_files = []

def check_dirs(start_path, target_path):
    if not os.path.exists(start_path):
        print("工作目录不存在,请确认!!")
        return False
    elif start_path == target_path:
        user_check = input("工作目录与目标目录相同,确认输入 YES !!")
        if user_check != "YES":        
            return False
        else:
            return True
    else:
        if not os.path.exists(target_path):
            os.mkdir(target_path)        
        # return os.path.abspath(start_path), os.path.abspath(target_path)
        return True
    
def check_file_extension_name(file,extension_name):
    ext = [ext for ext in extension_name]
    if file.split(".")[-1] in ext:
        return True
    else:
        return False

def  check_file_in_target_path(file,target_path):
    if os.path.exists(os.path.join(target_path,file)):
        return True
    else:
        return False

def copy_files(start_path, target_path,extension_name):        
    if check_dirs(start_path, target_path):
        for root,subdirs,files in os.walk(start_path): 
            if root == target_path:
                print("目标目录也在扫描范围内,已自动忽略")
                continue
            else:      
                for file in files:
                    if check_file_extension_name(file,extension_name):
                        if check_file_in_target_path(file,target_path):
                            repeat_files.append(file)                                
                        elif not check_file_in_target_path(file,target_path):
                            shutil.copy(os.path.join(root,file),target_path)
                            copyed_files.append(file)
    return copyed_files,repeat_files


                        
start_path = ".\\"
target_path = ".\\copy"
extension_name ="jpg","png","mp3","py"
# extension_name ="txt","py"

if __name__ == "__main__":
    copy_files(start_path, target_path,extension_name)
    # print("已经完成复制的文件:\n",copyed_files)
    print("目标目录下重名文件:\n",repeat_files)

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言