【问题标题】:not able to move file python无法移动文件python
【发布时间】:2019-01-02 18:59:00
【问题描述】:

之前已经给出了一些类似的解决方案,但似乎没有一个适合我。

代码:

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

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

谢谢!

【问题讨论】:

  • 错误提示找不到文件sample.tsv。尝试提供文件的绝对路径,这应该可以解决它。此外,还有更好的方法在 python 中移动文件。看看:stackoverflow.com/questions/8858008/…

标签: python mv python-watchdog


【解决方案1】:
  1. 永远不要使用os.system - 要在python 中运行子进程,请使用subprocess 模块。
  2. 在这种情况下,即使使用 subprocess 也太过分了,因为您想移动一个文件,因此您可以使用 shutil.move() 来做同样的事情,而无需调用单独的进程。
  3. os.listdir 只返回没有路径的文件名,所以你必须自己添加才能找到文件:os.path.join(self.datadir, f)
  4. 要高效地监视目录/文件而不是每 5 秒检查一次,您可以使用 pyinotify 模块 - 它使用高效的系统 API 来监视目录并在它发生变化时调用您的函数,不涉及轮询。李>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多