2017-10-08 90 views
0

我已经尝试了很多可能性,至今我在网上找到了,而我却无法让它工作。 我有这样的代码:如何使用Python复制包括子文件夹在内的所有文件

def copytree(src, dst, symlinks=False, ignore=None): 
    if not os.path.exists(dst): 
     os.makedirs(dst) 
    for item in os.listdir(src): 
     s = str(os.path.join(src, item)) 
     d = str(os.path.join(dst, item)) 
     if os.path.isdir(s): 
      copytree(s, d, symlinks, ignore) 
     else: 
      if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1: 
       shutil.copy2(s, d) 

使用此代码我可以全部文件从一个源文件夹复制到一个新的目标文件夹。 但是,如果源文件夹中有子文件夹,则这总是失败。 代码已经检查了要复制的项目是文件夹还是单个文件,那么这个代码的问题在哪里?

+0

有什么不好的['copytree'功能(https://docs.python.org/2/library/shutil.html#shutil.copytree)来自'shutil'模块? – rickdenhaan

回答

0

要达到此目的,您需要使用import osimport shutil

请参阅本为例:

import os 
import shutil 

for root, dirs, files in os.walk('.'): 
    for file in files: 
     path_file = os.path.join(root,file) 
     shutil.copy2(path_file,'destination_directory') 
相关问题