无法移动文件 python

not able to move file python

之前已经给出了一些类似的解决方案,但 none 似乎对我有用。

代码:

def watch_dir(self, prefix, dest):
    before = dict([(f, None) for f in os.listdir(self.data_dir)])
    while 1:
        time.sleep(5)
        after = dict([(f, None) for f in os.listdir(self.data_dir)])
        new_files = [f for f in after if not f in before and f.startswith(prefix)]
        before = new_files
        for f in new_files:
            os.system('mv {f} {dest}'.format(f=f, dest=dest))

当我打印 new_files 时,我得到 -> ('new_files = ', ['sample.tsv'])

但是 mv 命令给出了这个错误: mv: cannot stat 'sample.tsv': No such file or directory

有人可以帮助我了解这里可能出了什么问题吗?!

谢谢!

  1. 永远不要使用 os.system - 对于 python 中的 运行 子进程,请使用 subprocess 模块。
  2. 在这种情况下,即使使用 subprocess 也太多了,因为您想要移动一个文件,因此您可以使用 shutil.move() 来完成相同的操作,而无需调用单独的进程。
  3. os.listdir returns 只有没有路径的文件名,所以你必须自己添加才能找到文件:os.path.join(self.datadir, f)
  4. 要高效地观看 directories/files 而无需每 5 秒检查一次,您可以使用 pyinotify 模块 - 它使用高效的系统 api 来观看目录并将调用您的函数当它改变时,不涉及轮询。