简体   繁体   中英

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!

You can use the OS module.

Ex:

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

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

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.

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