Python批量拷贝文件

 批量拷贝文件:batchcopy.py

def batchcopyimgs(dir_orig, dir_desc, file_type):
    cwd = os.getcwd()
    path_orig = os.path.join(cwd, dir_orig)
    path_desc = os.path.join(cwd, dir_desc)
    if not os.path.exists(path_orig):
        print("path_orig is not exist!")
        raise

    if not os.path.exists(path_desc):
        os.makedirs(path_desc)

    #for parent, dirname, filenames in os.walk(path_orig):
    #    print("\nparent:", parent, " dirname:", dirname, " filenames:", filenames)
    file_list_1 = os.listdir(path_orig)
    for file in file_list_1:

        camera_id = file.split("_")[-1]
        filepath = os.path.join(path_orig, file)
        if os.path.isdir(filepath):
            file_list_2 = os.listdir(filepath)
            for file2 in file_list_2:
                filepath2 = os.path.join(filepath, file2)
                if filepath2.endswith(file_type):
                    #print("copying", filepath2)
                    new_name = "C"+camera_id + "_" + dir_orig + "_" + file2
                    path_new_desc = os.path.join(path_desc, new_name)
                    print("copying path_new_desc:", path_new_desc)
                    shutil.copy(filepath2, path_new_desc)
            sleep(0.1s)
else: print("not directory,continue...") def main(): dir_desc = "JPEGImages" dir_orig = "data_acquisition" file_type = ".jpeg" batchcopyimgs(dir_orig, dir_desc, file_type) if __name__ == "__main__": main()

注意点1:

 批量拷贝文件时,如果需要对拷贝的文件重命名,只需在目标路径中指定上新文件名,如目标路径中只是文件夹,则为同名拷贝

shutil.copy(filepath_orig, filepath_desc)

注意点2:

 如果直接使用shutil.copy(filepath2, path_new_desc),由于拷贝需要一定的时间,在拷贝的过程中会出现文件漏拷贝问题

 解决方法:在拷贝文件操作的下面加上sleep(0.1) ,来保证拷贝过程正常完成,注:括号里的数据为ms级,可根据拷贝操作需要的时间自行调节

 

posted @ 2021-03-03 23:42  jimchen1218  阅读(285)  评论(0编辑  收藏  举报