繁体   English   中英

如何有条件地将文件从一个目录移动到另一个目录?

[英]How to conditionally move files from one directory to another?

我正在尝试使用 Shutil 有条件地将一些文件从一个目录移动到另一个目录。

这是我的代码:

files = [
 '152_rand_6762_1540.npz',
 '14_rand_7652_-2532.npz',
 '1079_rand_1947_-484.npz',
 '152_rand_6209_1217.npz',
 '928_rand_3784_-934.npz',
 '984_rand_3992_-10.npz',
 '1245_rand_3214_-91.npz']

test_samples = [984, 152, 409, 1245, 12, 1336]

source = 'D:/task/rand/' 
dest = 'D:/task/xtra_rand/'

def move_subset(source):
    files = os.listdir(source)
    count = 0
    for file in files:
        pathz = os.path.join(source, file)
        for num in test_samples:
            if str(num) == file.split('_')[0]:
                if not os.path.exists(dest+file):
                    shutil.move(os.path.join(source,file),os.path.join(dest, file))
                    print(num , 'found')
                    count += 1
                else:
                    os.remove(dest+file)
                    shutil.move(os.path.join(source,file),os.path.join(dest, file))
                    count += 1       
            print('moved: ', count)

move_subset(source)

它运行了一段时间,然后给出了这个错误信息:

 FileNotFoundError: [Errno 2] No such file or directory: 'D:/task/rand/152_rand_1355_512.npz

失败时移动的文件也会丢失,因为它既不在source目录中,也不在dest目录中。

有谁知道如何解决这个问题或任何其他有条件地移动文件的方法?

谢谢你们的回应。 我仍然不确定是什么导致我的代码出现问题,但我想出了下面的代码,它似乎更健壮。 为遇到相同问题的任何人发帖。

def move_subset(source):
    files = os.listdir(source)
    count = 0
    for file in files:
        num = int(file.split('_')[0])
        if num in test_samples:
            target = os.path.join(dest, file)
            if os.path.exists(target):
                os.remove(target)
            shutil.move(os.path.join(source, file), os.path.join(dest, file))
            print('%s found' % num)
            count += 1
        print('moved: %d' % count)

move_subset(source)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM