简体   繁体   中英

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.

  • kplr006933899 -2009131105131_ llc .fits
  • kplr006933899-2009131105131_ lpd-targ .fits
  • kplr006933899-2012151031540_ slc .fits
  • kplr006933899-2012151031540_ spd-targ .fits

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

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
>>> "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM