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

时间:2010-03-14 13:19:10

标签: python file search

如何搜索文件有一个已知的文件扩展名,如.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

4 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

非递归:

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

答案 3 :(得分:-1)

你可以写的很简单:

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)]