Python 将多个文件复制到新文件夹中
我有一个包含几个文本文件的文件夹。我该如何使用python复制这些文件的所有副本,并将副本放在新文件夹中?我建议查看以下帖子: 应该可以了。使用shutil.copyfilePython 将多个文件复制到新文件夹中,python,copy,Python,Copy,我有一个包含几个文本文件的文件夹。我该如何使用python复制这些文件的所有副本,并将副本放在新文件夹中?我建议查看以下帖子: 应该可以了。使用shutil.copyfile import shutil shutil.copyfile(src, dst) 来源:您可以使用glob模块选择.txt文件: import os, shutil, glob dst = 'path/of/destination/directory' try: os.makedirs(dst) # create
import shutil
shutil.copyfile(src, dst)
来源:您可以使用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
模块仅包含两个功能:glob
和iglob
()。它们都根据Unix shell使用的规则查找与指定模式匹配的所有路径名,但是glob.glob
返回一个列表,而glob.iglob
返回一个生成器。到目前为止您尝试了什么?当我们知道您到目前为止所做的事情时,我们会更容易提供帮助。os.system
不受欢迎subprocess.call
是推荐的备选方案:在这种情况下,两者都不应使用。Python可以很好地读取目录列表(并且可以处理文件名中的空白)os.listdir()
感谢@Tshepang和jordanm的反馈。我相应地更新了我的建议答案。除非您再次需要ls\u dir
,否则您可以将os.listdir(src\u path)中的文件缩短为。我还希望您避免使用像file
这样的词来表示任意变量,因为file()
是一个内置函数。makedirs(dst)
如果目标已经存在,则会失败,而不像mkdir-p
Good catch。我在它周围添加了异常处理。
import shutil
shutil.copytree("abc", "copy of abc")
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)