views:

74

answers:

4

how to search for file's has a known file extension like .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  A: 

I believe you want to do something like similar to this: /dir/to/search/*.extension?

This is called glob and here is how to use it:

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

Edit: and here is the documentation: http://docs.python.org/library/glob.html

adamse
yea this what i want, but does it work in windows ??
Rami Jarrar
There is no reason for this not to work. From the docs "This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell". (I also believe that this is the correct solution to your problem, one should prefer built-in functionality before creating ones own.)
adamse
A: 

Non-recursive:

for x in os.listdir(dir):
    if x.endswith(fext):
        filename = os.path.join(dir, x)
        # do your stuff here
Tuomas Pelkonen
Do we need `os.path.join`? I guess `x` itself is `filename`.
TheMachineCharmer
x is only the filename without the directory name, at least in python 2.5 and python 2.6 IIRC
Tuomas Pelkonen
This has a bug—it catches `.epy` files when you are looking for `.py` files. Also, `glob.glob` is the right tool for this job.
Mike Graham
Mike: it won't catch `.epy` files when looking for `.py` files. It will when looking for `py` files.
ΤΖΩΤΖΙΟΥ
+1  A: 
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)
ghostdog74
A: 

You can write is as simple as:

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)]
mojbro
Out of curiosity - why was this solution voted down?
mojbro