Rami Jarrar
Rami Jarrar

Reputation: 4643

how to search for file's has a known file extension like .py?

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

Upvotes: 1

Views: 1815

Answers (4)

mojbro
mojbro

Reputation: 1529

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

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 343211

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)

Upvotes: 1

Tuomas Pelkonen
Tuomas Pelkonen

Reputation: 7831

Non-recursive:

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

Upvotes: 0

ase
ase

Reputation: 13489

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

Upvotes: 4

Related Questions