2012-07-28 27 views
3

我有一个文件夹包含几个文本文件。我将如何去使用python来制作这些文件的每个人的副本,并将副本放在一个新的文件夹中?将几个文件复制到新文件夹中

+2

你到目前为止尝试过什么?当我们知道您到目前为止所做的工作时,帮助起来会更容易。 – Levon 2012-07-28 00:44:58

回答

1

我建议看这个帖子:How do I copy a file in python?

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

应该这样做。

+1

'os.system'不鼓励; 'subprocess.call'是推荐的替代方法:http://docs.python.org/library/subprocess#replacing-os-system – Tshepang 2012-07-28 01:05:46

+1

在这种情况下,两者都不应该使用。 Python可以读取一个很好的目录列表(以一种处理文件名空白的方式)。 'os.listdir()' – jordanm 2012-07-28 02:06:28

+0

谢谢你的反馈@Tshepang和jordanm。我相应地更新了我的建议答案。 – cloksmith 2012-07-29 05:34:01

0

使用shutil.copyfile

import shutil 
shutil.copyfile(src, dst) 
2
import shutil 
shutil.copytree("abc", "copy of abc") 

来源:docs.python.org

2

可以使用水珠模块来选择您的.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功能:globiglobsee documentation)。根据Unix shell使用的规则,它们都找到与指定模式匹配的所有路径名,但glob.glob返回一个列表,glob.iglob返回一个生成器。

+0

'makedirs(dst)'如果目的地已经存在,则失败,不像'mkdir -p' – 2016-01-26 01:18:57

+0

好。我添加了异常处理。 – 2016-03-03 12:56:11

相关问题