Python - 在目录中复制多个文件

时间:2015-12-12 15:56:17

标签: python copy shutil

我是Python新手并尝试编写自动化测试程序。更具体地说,我试图将几个.xlsx文件从一个目录复制到另一个目录。我已经进行了彻底的研究并且部分地在那里进行了研究。我的代码在下面,它没有返回和错误,但没有完成我想要做的事情。我相信我的代码不够精细(我在目录层面陷入困境)。简而言之:文件A包含c,d,e,f.1,f.2,f.3(所有Excel文档)。文件B为空。我试图将f.1,f.2和f.3复制到文件B中。我相信我也需要在某些时候添加startswith函数。任何帮助表示赞赏。谢谢!

import os
import shutil
import glob

source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'

src_files = os.listdir('C:/Users/acars/Desktop/a')

for file_name in src_files:
    full_file_name = os.path.join('C:/Users/acars/Desktop/a','a') #'a' incorrect
    if (os.path.isfile(full_file_name)):
        shutil.copy(full_file_name, dest1)
    else:
        break 

1 个答案:

答案 0 :(得分:1)

使用变量sourcedest1

source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'

src_files = os.listdir(source)

for file_name in src_files:
    if not file_name.startswith('f'):
        continue
    src = os.path.join(source, file_name)  # <--
    dst = os.path.join(dest1, file_name)   # <--
    shutil.copy(src, dst)