1

I have a list of my filenames that I've saved as follows:

filelist = os.listdir(mypath)

Now, suppose one of my files is something like "KRAS_P01446_3GFT_SOMETHING_SOMETHING.txt".

However, all I know ahead of time is that I have a file called "KRAS_P01446_3GFT_*". How can I get the full file name from file list using just "KRAS_P01446_3GFT_*"?

As a simpler example, I've made the following:

mylist = ["hi_there", "bye_there","hello_there"]

Suppose I had the string "hi". How would I make it return mylist[0] = "hi_there".

Thanks!

4 Answers 4

2

In the first example, you could just use the glob module:

import glob
import os
print '\n'.join(glob.iglob(os.path.join(mypath, "KRAS_P01446_3GFT_*")))

Do this instead of os.listdir.

The second example seems tenuously related to the first (X-Y problem?), but here's an implementation:

mylist = ["hi_there", "bye_there","hello_there"]
print '\n'.join(s for s in mylist if s.startswith("hi"))
Sign up to request clarification or add additional context in comments.

Comments

0

If you mean "give me all filenames starting with some prefix", then this is simple:

[fname for fname in mylist if fname.startswith('hi')]

If you mean something more complex--for example, patterns like "some_*_file" matching "some_good_file" and "some_bad_file", then look at the regex module.

Comments

0
mylist = ["hi_there", "bye_there","hello_there"]
partial = "hi"
[fullname for fullname in mylist if fullname.startswith(partial)]

Comments

0

If the list is not very big, you can do a per item check like this.

def findMatchingFile (fileList, stringToMatch) :
    listOfMatchingFiles = []

    for file in fileList:
        if file.startswith(stringToMatch):
            listOfMatchingFiles.append(file)

    return listOfMatchingFiles

There are more "pythonic" way of doing this, but I prefer this as it is more readable.

1 Comment

May be, may be not. Depends on, if the person asking knows what a generator is and how yield works. By my experience that is something few people know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.