Python 查找、重命名和替换文件
我需要用补丁目录中提供的文件更新现有目录。 这就是我要开始的。所有这些都被我注释掉了,然后我尝试构建每一行Python 查找、重命名和替换文件,python,Python,我需要用补丁目录中提供的文件更新现有目录。 这就是我要开始的。所有这些都被我注释掉了,然后我尝试构建每一行 # $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
# $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";
如前一篇文章所述,我对你根据所提供的信息所遵循的课程表示怀疑。根据给出的文档,有更好的网站/教程可以免费帮助您学习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)
这看起来像伪代码,而不是Python?可能需要对其进行编辑,以便清楚说明什么是评论,什么不是评论。如果你在两周后还不能区分伪代码和真代码,那么这门课就是在浪费你的时间。你试过什么?你能给我们一些你写的代码的例子吗?它在哪里被破坏了,你期望什么?我们都可以为您编写代码,但是如果您试图学习python,那就没有太大帮助了。是的,这是我刚刚亲手编写的psuedo代码,其中包含了一些粗略的想法。它在任何情况下,形状或形式都不是真正的代码。我睡了一会儿,现在我要再打一针。请继续关注。我将此功能调高了一点,并使用windows powershell来完成此操作。SQL server和outlook中出现了大量范围扩展,因此powershell是一个简单的选择。非常简单易学,尽管我认为python会更好。