Timur Cetindag
Timur Cetindag

Reputation: 7

looping through specific files in python

So I have a script where I loops through a set of files in a folder. After retrieving the list of files in that particular directory, how do I specify which files I want to use in the script?

target = './directory/'

for file in listdir(target):

Now I have several different files in the same folder.

They all are part of the same group, which is denoted by "kplr006933899". How can I specify parts of the strings as different variable in order to specify which files I want to loop through?

Like for example:

def function(name,types)

where you could write when called:

function(kplr006933899,[slc,llc])

Upvotes: 1

Views: 523

Answers (2)

Simeon Visser
Simeon Visser

Reputation: 122376

There are multiple ways of doing this. First way:

import fnmatch

def my_function(name, types):
    result = []
    for t in types:
        pattern = "{}*{}.fits".format(name, t)
        for filename in fnmatch.filter(listdir(target), pattern):
            result.append(filename)
    return result

You can call this function with: my_function("kplr006933899", ["slc", "llc"]). The fnmatch.filter function performs the pattern matching with your pattern and the given filenames.

The second way is to use glob:

result = []
for t in types:
    result.extend(glob.glob("{}/{}*{}.fits".format(target, name, t)))
return result

Upvotes: 3

ev-br
ev-br

Reputation: 26040

>>> "kplr" in  "kplr006933899-2009131105131_llc.fits"
True
>>> 
>>> "kplR" in  "kplr006933899-2009131105131_llc.fits"
False
>>> 

Notice that you need to put quotes to denote a string function("kplr006933899", [slc, llc]), otherwise kplr006933899 will be interpreted as a variable.

Upvotes: 0

Related Questions