查找,重命名和替换文件

时间:2016-01-20 04:59:46

标签: python

我需要使用Patch目录中提供的文件更新现有目录。 这就是我的开始。所有这些都由我评论,然后我尝试构建每一行。

# $SourceDirectory = Patch folder that has files in any number of sub folders
# $DestDirectory = Application folder that has the files that need patching 
# $UnMatchedFilesFolder = A Folder where SourceFiles go that don't have a match in $DestDirectory
# import os.path
# import os.listdir
#
# Create list1 of files from $SourceDirectory
# For each file (excluding directory names) in List1 (including subfolders), search for it in $DestDirectory and its subfolders;
# If you find the file by the same name, then create a backup of that file with .old;
#   move $DestDirectoryPathAndFile to $DestDirectoryPathAndFile.old;
#   print "Creating backup of file";
#   After the backup is made, then copy the file from the $SourceDirectory to the;
#   exact same location where it was found in the $DestDirectory.  ;
# Else;
#   move file to UnmatchedFilesDirectory.;
#  If the number of files in $UnMatchedFilesDirectory =/ 0;
#   Create list3 from $UnmatchedFilesDirectory
#  print "The following files in $UnMatchedFilesDirectory will need to be installed individually";
# Print "Automated Patching completed.";

# Print "Script completed"; 

1 个答案:

答案 0 :(得分:1)

正如前一篇文章所述,我对你所遵循的课程持怀疑态度。根据给出的文档,有更好的网站/教程免费提供,以帮助您学习Python /编程。也就是说,Stack Overflow是一个友好的地方,所以我希望能为您提供有助于您的信息:

import os
source_dir =r"D:\temp"
dest_dir=r"D:\temp2"

for root, dirs, files in os.walk(source_dir):
    # os.walk 'root' steps through subdirectories as we iterate
    # this allows us to join 'root' and 'file' without missing any sub-directories
    for file in files:
        exist_path = os.path.join(root, file)
        # expected_file represents the fullpath of a file we are looking to create/replace
        expected_file = exist_path.replace(source_dir, dest_dir)
        current = os.path.join(root, file)
        if os.path.exists(expected_file):
            print "The file %s exists, os.rename with '.old' before copying %s" % (current, exist_path)
            # .. note:: we should rename to .bkp here, then we would correctly copy the file below without conflict
        print "Now %s doesn't exist, we are free to copy %s" % (expected_file, exist_path)