Python 2.7 |复制文件夹结构文件

时间:2018-01-02 13:53:41

标签: python-2.7 copy

具有以下目录结构。

jobs/

    jobname1/

        builds/

        config.xml

    jobname2/

        builds/

        config.xml

在作业文件夹下有多个作业名称。 我希望将所有config.xml文件复制到另一个备份目录,而不会错过其jobname文件夹结构。

请你帮我理解如何以更有效的方式使用shutil libraray。

我的目标文件夹备份结构如下所示

备份/

jobs/

    jobname1/

        config.xml

    jobname2/

        config.xml

请帮忙。 请在下面找到我的实际要求。

编写python2.7 scrpt的算法

    1. git clone Backup folder , where Backup is empty folder
    2. Find list of files having file name "config.xml in the HOME folder
    3. Copy all config.xml files to Backup folder with out changing the folder structure
            3.1. If config.xml is new file then git add  all config.xml to git repository , and commit followed by git push
            3.2. If config.xml is existing and unchanged then git push is not required
            3.3. If config.xml is existing and modified then commit followed by git push

1 个答案:

答案 0 :(得分:0)

我找到了逻辑。可能这可能对某人有用。对代码感到遗憾,因为它是新手级别。

                def walkfs(self,findfile):
                    ## dictionary to store full path of each source findfile
                    matches_fullpath_dict = {}
                    ## dictionary to store relative path of each findfile
                    matches_trunc_dict = {}
                    ## dictionary to store full path of each target file location
                    matches_target_fullpath_dict = {}
                    i =0
                    source = self.jenkins_Home
                    destination = self.backupRepositoryPath
                    for root, dirnames, filenames in os.walk(source):            
                        for filename in fnmatch.filter(filenames, findfile):
                            i=i+1
                            matches_fullpath_dict[i]=os.path.join(root, filename)
                            matches_trunc_dict[i]=os.path.join(root.replace(source,""), filename)                
                            matches_target_fullpath_dict[i]=os.path.join( os.path.sep, destination + root.replace(source,""))


                    keys = matches_target_fullpath_dict.keys()
                    for key in keys:
                        if not os.path.exists(matches_target_fullpath_dict.get(key)):
                            try:
                                os.makedirs(matches_target_fullpath_dict.get(key))
                            except OSError:
                                pass

                    keys = matches_target_fullpath_dict.keys()
                    for key in keys:
                        shutil.copy2(matches_fullpath_dict.get(key,None), matches_target_fullpath_dict.get(key,None))