【发布时间】:2012-07-28 00:38:01
【问题描述】:
我有一个包含多个文本文件的文件夹。我将如何使用 python 复制所有这些文件并将副本放在新文件夹中?
【问题讨论】:
-
到目前为止你尝试过什么?当我们知道您到目前为止所做的事情时,会更容易提供帮助。
我有一个包含多个文本文件的文件夹。我将如何使用 python 复制所有这些文件并将副本放在新文件夹中?
【问题讨论】:
import shutil
shutil.copytree("abc", "copy of abc")
【讨论】:
您可以使用 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 个函数:glob 和 iglob (see documentation)。它们都根据 Unix shell 使用的规则找到与指定模式匹配的所有路径名,但 glob.glob 返回一个列表,glob.iglob 返回一个生成器。
【讨论】:
makedirs(dst) 失败,如果目的地已经存在,不像mkdir -p
我建议看看这篇文章: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
os.listdir()
ls_dir,否则您可以将其缩短为for file in os.listdir(src_path)。我还希望您避免使用像 file 这样的词来表示任意变量,因为 file() 是一个内置函数。
使用shutil.copyfile
import shutil
shutil.copyfile(src, dst)
【讨论】: