【问题标题】:Moving all contents of a directory to another in Python在 Python 中将目录的所有内容移动到另一个目录
【发布时间】:2020-04-24 19:27:35
【问题描述】:

我一直在尝试解决这个问题几个小时,但没有运气。我有一个目录列表,其中包含自己的子目录和其他文件。我试图遍历所有这些并将它们的所有内容移动到特定位置。我尝试了shutil和glob,但我无法让它工作。我什至尝试使用subprocess.call 运行shell 命令,但这也不起作用。我知道它不起作用,因为我无法正确应用它,但我找不到将目录的所有内容移动到另一个目录的任何解决方案。

files = glob.glob('Food101-AB/*/')
dest = 'Food-101/'

if not os.path.exists(dest):
    os.makedirs(dest)
    subprocess.call("mv Food101-AB/* Food-101/", shell=True)

    # for child in files:
    #   shutil.move(child, dest)

我正在尝试将 Food101-AB 中的所有内容移至 Food-101

【问题讨论】:

    标签: python glob shutil


    【解决方案1】:

    shutil 标准库的模块是要走的路:

    >>> import shutil
    >>> shutil.move("Food101-AB", "Food-101")
    

    如果您不想移动 Food101-AB 文件夹本身,请尝试使用:

    import shutil
    import os
    
    for i in os.listdir("Food101-AB"):
        shutil.move(os.path.join("Food101-AB", i), "Food-101")
    

    更多关于move函数的信息: https://docs.python.org/3/library/shutil.html#shutil.move

    【讨论】:

      【解决方案2】:

      尝试将call 函数更改为run,以便为您的shell 命令检索stdoutstderrreturn code

      from subprocess import run, CalledProcessError
      source_dir = "full/path/to/src/folder"
      dest_dir = "full/path/to/dest/folder"
      try:
          res = run(["mv", source_dir, dest_dir], check=True, capture_output=True)
      except CalledProcessError as ex:
          print(ex.stdout, ex.stderr, ex.returncode)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-12
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 2014-10-16
        相关资源
        最近更新 更多