mizenetofa1989
mizenetofa1989

Reputation: 117

Python 2.7 check if there is a file with a specific file name

I want to check if there is a file in a folder that its name contains a specific string, like:

folder:

-- hi.txt

-- bye.txt

-- bedanagain.txt

-- dan1.txt

-- dan2.txt

-- gray.txt

return true if in the folder there is a file with "dan" in its name.

Plus, If possible, I need to use the most well known imports (the customer is nervous about using unknown open source packages) and the smallest number of imports.

I tried using os.path.exists but I found that it works only if you have the full filename, and it wasn't able to search for a file name that contains some string.

I tried:

import os
print os.path.exists('./dan') // false
print os.path.exists('./dan*') // false
print os.path.exists('./*dan') // false

That is also why this is not a duplicate - I checked the mentioned feed, it deals with "if a file exists" and not "if a file with some string in its name exists"

Thanks!

Upvotes: 0

Views: 7351

Answers (3)

Aayush Bhatnagar
Aayush Bhatnagar

Reputation: 143

You can use os.listdir("dir path") to get all files in directory in list and check for file name in that list:

import os
def check_file():
    x = os.listdir("path to dir")
    for i in x:
        if ["hi","bye","bedanagain","dan1","dan2","gray"] in i:
            return True

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

You can use the OS module.

Ex:

import os
for file in os.listdir(Path):
    if "dan" in file:
        print(file)

Upvotes: 4

Alex Hawking
Alex Hawking

Reputation: 1245

If you are using mac, try having a look at the 'os' module (it should be built into your computer) you can import it with:

import os

You can run shell commands from within python using

os.system("your command")

For example

os.system("echo "This is terminal"")

I'm sure there is a terminal command that will let you check folders for specific files.

Upvotes: 0

Related Questions