3

I think the title explains it all. I need to check existence for a file that contains the word data in its name. I tried something like that os.path.exists(/d/prog/*data.txt) but that doesn't work.

3 Answers 3

3

Try glob for it:

from glob import glob
if glob('/d/prog/*data.txt'):
    # blah blah 
Sign up to request clarification or add additional context in comments.

Comments

3

You can't just do it with os.path.exists -- it expects full pathname. If do not know exact filename, you should first find this file on filesystem (and when you do, it proves that file exists).

One option is to list directory (-ies), and find file manually:

>>> import os
>>> file_list = os.listdir('/etc')
>>> [fn for fn in file_list if 'deny' in fn]
['hostapd.deny', 'at.deny', 'cron.deny', 'hosts.deny']

Another and more flexible option is to use glob.glob, which allows to use wildcards such as *, ? and [...]:

>>> import glob
>>> glob.glob('/etc/*deny*')
['/etc/hostapd.deny', '/etc/at.deny', '/etc/cron.deny', '/etc/hosts.deny']

Comments

1

If you are on Windows:

>>> import glob
>>> glob.glob('D:\\test\\*data*')
['D:\\test\\data.1028.txt', 'D:\\test\\data2.1041.txt']

Comments

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.