【问题标题】:How to skip .hg / .git / .svn directories while recursing tree in python如何在python中递归树时跳过.hg / .git / .svn目录
【发布时间】:2011-08-15 19:52:23
【问题描述】:

我有一个 python 脚本,我一直在拼凑(我第一次尝试 python)。

脚本递归查找 XCode 项目文件的文件夹;该脚本工作正常,但我想对其进行调整以跳过任何 .svn(或 .hg 或 .git)文件夹,这样它就不会尝试修改源存储库。

这是递归搜索的脚本

for root, dirnames, files in os.walk('.'):
    files = [f for f in files if re.search("project\.pbxproj", f)]
    for f in files:
        filename = os.path.join(root, f)
        print "Adjusting BaseSDK for %s" % (filename)
        ...

如何排除存储库子树?

【问题讨论】:

  • 你看过 os.walk 文档了吗? docs.python.org/library/os.html#os.walk。确切的解决方案在文档中。 dirnames.remove(".svn")
  • 刚遇到这里,因为我想删除项目中的所有 .svn 文件,命令 svn export 只是在不需要脚本的情况下执行此操作(在 hg 和 git 中只有一个文件夹您必须删除的项目的根目录)。
  • @S.Lott 感谢您指出文档中的位置;不知道为什么我之前错过了。

标签: python directory os.walk


【解决方案1】:

在处理文件之前,您可以检查文件名中的第一个字符是否以“.”开头,如果是,则继续循环中的下一项。

for root, dirnames, files in os.walk('.'):
    files = [f for f in files if re.search("project\.pbxproj", f)]
    for f in files:
        ### EDIT START
        if f[0] == ".":
            continue
        ### EDIT FINISH

        filename = os.path.join(root, f)
        print "Adjusting BaseSDK for %s" % (filename)

【讨论】:

  • .hg、.git、.svn 是文件夹。另请参阅上面有问题的评论。
【解决方案2】:

正如 S.Lott 在他的评论中所说,os.walk 的文档中提到了这一点。以下应该可以正常工作:

for root, dirs, files in os.walk("."):
    if ".hg" in dirs:
        dirs.remove(".hg")
    for f in files:
        print os.path.join(root, f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多