首页 > 解决方案 > 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!

标签: pythonstringpython-2.7filenames

解决方案


您可以使用该OS模块。

前任:

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

推荐阅读