1

I'm trying to make a code that can move files from one folder to another. For instance, I have files named 0001.jpg, 0002.jpg ... and so on in /test1/ folder and want to move those files to /test3/ folder if the same file name doesn't exist in /test2/. So, if there's 0001.jpg both in folder /test1/ and /test2/ the file in /test1/ won't be moved to /test3/ folder but if there's 0002.jpg in /test1/ and not in /test2/, it moves to /test/3.

I've tried to write the code on my own but it won't work. Can you please help with this? Thanks in advance!

import os
import shutil

def Move_files(root_path, refer_path, out_path) :
    root_path_list= [file for file in os.listdir(root_path)]
    refer_path_list= [file for file in os.listdir(refer_path)]

    for file in root_path_list:
        if refer_path_list in root_path_list:
            shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(refer_path, file)))

if __name__ == '__main__' :
    Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")
4

3 回答 3

1

更新:您可以使用检查文件是否存在于您的其他目录中os.path.exists,然后仅在它不存在时移动它/test2/

if not os.path.exists(os.path.join(refer_path, file)):
    shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(refer_path, file)))

此外,os.listdir只接受一个参数,即要列出文件的目录的路径。我认为您想将您的shutil.move陈述更改为:shutil.move(os.path.join(root_path, file),os.path.join(out_path, file))

于 2020-04-08T03:03:12.400 回答
1

您可以使用set来查找文件列表之间的差异。我添加了一个isfile检查以忽略子目录(例如,linux 中的“.”和“..”目录),并且由于shutil.move接受目标目录,因此无需构建目标文件名。

import os
import shutil

def Move_files(root_path, refer_path, out_path) :
    root_files = set(filename for filename in os.listdir(root_path)
        if os.path.isfile(filename))
    refer_files = set(filename for filename in os.listdir(refer_path)
        if os.path.isfile(filename))
    move_files = root_files - refer_files

    for file in move_files:
        shutil.move(os.path.join(root_path, file), out_path)

if __name__ == '__main__' :
    Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")
于 2020-04-08T03:19:57.500 回答
1

尝试这个

import os
import shutil

def Move_files(root_path, refer_path, out_path) :
    root_path_list= [file for file in os.listdir(root_path)]
    refer_path_list= [file for file in os.listdir(refer_path)]

    for file in root_path_list:
        if file not in refer_path_list:
            shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(out_path, file)))

if __name__ == '__main__' :
    Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")
于 2020-04-08T03:13:46.933 回答