【问题标题】:how to search for file's has a known file extension like .py?如何搜索具有已知文件扩展名(如 .py)的文件?
【发布时间】:2010-03-14 13:19:10
【问题描述】:

如何搜索具有已知文件扩展名的文件,例如 .py ??

fext = raw_input("Put file extension to search: ")
dir = raw_input("Dir to search in: ")

##Search for the file and get the right one's

【问题讨论】:

    标签: python file search


    【解决方案1】:

    我相信你想做类似这样的事情:/dir/to/search/*.extension?

    这叫做 glob,下面是如何使用它:

    import glob
    files = glob.glob('/path/*.extension')
    

    编辑:这里是文档:http://docs.python.org/library/glob.html

    【讨论】:

    • 没有理由不这样做。来自文档“这是通过同时使用 os.listdir() 和 fnmatch.fnmatch() 函数来完成的,而不是通过实际调用子shell”。 (我也相信这是解决您问题的正确方法,在创建自己的功能之前应该更喜欢内置功能。)
    【解决方案2】:
    import os
    root="/home"
    ext = raw_input("Put file extension to search: ")
    path = raw_input("Dir to search in: ")
    for r,d,f in os.walk(path):
        for files in f:
             if files.endswith(ext):
                  print "found: ",os.path.join(r,files)
    

    【讨论】:

      【解决方案3】:

      非递归:

      for x in os.listdir(dir):
          if x.endswith(fext):
              filename = os.path.join(dir, x)
              # do your stuff here
      

      【讨论】:

      • 我们需要os.path.join吗?我猜x 本身就是filename
      • x 只是没有目录名的文件名,至少在 python 2.5 和 python 2.6 IIRC 中
      • 这有一个错误——当您查找 .py 文件时,它会捕获 .epy 文件。此外,glob.glob 是完成这项工作的正确工具。
      • Mike:在查找.py 文件时,它不会捕获.epy 文件。查找py 文件时会这样做。
      【解决方案4】:

      你可以这么写:

      import os
      ext = raw_input("Put file extension to search: ")
      path = raw_input("Dir to search in: ")
      matching_files = [os.path.join(path, x) for x in os.listdir(path) if x.endswith(ext)]
      

      【讨论】:

        猜你喜欢
        • 2013-06-02
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多