【问题标题】:How to conditionally move files from one directory to another?如何有条件地将文件从一个目录移动到另一个目录?
【发布时间】:2020-05-22 20:43:10
【问题描述】:

我正在尝试使用 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 目录中。

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

【问题讨论】:

  • 从这个角度来看,在我看来,在您的“其他”区域中,您正试图通过组合 dest+file 来删除文件,这可能会引发错误。如果你执行 os.remove(os.path.join(dest,file)) 会发生什么?
  • @RyanBarnes 感谢您的回复,但不幸的是我仍然遇到同样的错误。
  • 我试了你的代码,做了一点小改动,让它适应我的电脑,而且它似乎工作正常。你想看看什么有效吗,还是你认为这无济于事?
  • 请提供完整的错误消息,包括给出该消息的源代码行
  • 代码之前运行过吗?我问是因为您使用的是 move 命令,这意味着文件不再位于原始目标中。如果是这种情况,remove 命令返回错误是有道理的。如果还是不行,你确定文件路径和名称是正确的吗?

标签: python file move shutil errno


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2014-12-04
    相关资源
    最近更新 更多