0

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!

mizenetofa1989
  • 117
  • 2
  • 16
  • Please follow the posting guidelines, i.e., post your attempts and what's wrong with them. – nicoco May 30 '18 at 06:23
  • Also, if by "the most well known imports" you mean the python standard library, you're in trouble: it's all open source. – nicoco May 30 '18 at 06:24
  • You can use the `os` or `glob` module. – Rakesh May 30 '18 at 06:25
  • Possible duplicate of [How to check whether a file exists?](https://stackoverflow.com/questions/82831/how-to-check-whether-a-file-exists) – Austin May 30 '18 at 06:25

3 Answers3

4

You can use the OS module.

Ex:

import os
for file in os.listdir(Path):
    if "dan" in file:
        print(file)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
2

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
0

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.

Alex Hawking
  • 1,125
  • 5
  • 19
  • 35