Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多个文件复制到新文件夹中_Python_Copy - Fatal编程技术网

Python 将多个文件复制到新文件夹中

Python 将多个文件复制到新文件夹中,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

我有一个包含几个文本文件的文件夹。我该如何使用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 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)