【问题标题】:Copying several files into new folder将多个文件复制到新文件夹中
【发布时间】:2012-07-28 00:38:01
【问题描述】:

我有一个包含多个文本文件的文件夹。我将如何使用 python 复制所有这些文件并将副本放在新文件夹中?

【问题讨论】:

  • 到目前为止你尝试过什么?当我们知道您到目前为止所做的事情时,会更容易提供帮助。

标签: python copy


【解决方案1】:
import shutil
shutil.copytree("abc", "copy of abc")

来源:docs.python.org

【讨论】:

    【解决方案2】:

    您可以使用 glob 模块来选择您的 .txt 文件:

    import os, shutil, glob
    
    dst = 'path/of/destination/directory'
    try:
        os.makedirs(dst) # create destination directory, if needed (similar to mkdir -p)
    except OSError:
        # The directory already existed, nothing to do
        pass
    for txt_file in glob.iglob('*.txt'):
        shutil.copy2(txt_file, dst)
    

    glob 模块仅包含 2 个函数:globiglob (see documentation)。它们都根据 Unix shell 使用的规则找到与指定模式匹配的所有路径名,但 glob.glob 返回一个列表,glob.iglob 返回一个生成器。

    【讨论】:

    • makedirs(dst) 失败,如果目的地已经存在,不像mkdir -p
    • 好收获。我在它周围添加了异常处理。
    【解决方案3】:

    我建议看看这篇文章:How do I copy a file in python?

    ls_dir = os.listdir(src_path)    
    for file in ls_dir:
        copyfile(file, dest_path)
    

    应该可以的。

    【讨论】:

    • os.system 不鼓励; subprocess.call 是推荐的替代方案:docs.python.org/library/subprocess#replacing-os-system
    • 在这种情况下,都不应该使用。 Python 可以很好地读取目录列表(并且以处理文件名中的空格的方式)。 os.listdir()
    • 感谢@Tshepang 和 jordanm 的反馈。我相应地更新了我的建议答案。
    • 除非您再次需要ls_dir,否则您可以将其缩短为for file in os.listdir(src_path)。我还希望您避免使用像 file 这样的词来表示任意变量,因为 file() 是一个内置函数。
    【解决方案4】:

    使用shutil.copyfile

    import shutil
    shutil.copyfile(src, dst)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2015-05-23
      • 2022-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多