Felipe Rios
Felipe Rios

Reputation: 101

Check if file exists in list of directories

I have a list of directories, and a file name. I'd like to check if this file name exists in any of the directories, if it does exist then the code passes, if not then we'll error out. I'm having some trouble with the next step though, here's what I have.

for value in d.values():
    for path in value:
        if exists(path + '/' + filename):
            print 'True'
        else:
            print 'False'

Here's the list of my test output:

False
False
False
False
False
False
False
False
False
False
False
False
False
False
True
True
True
True

As you can see this fails a lot, but there is some passing cases here, the fact that is passes once is good enough for me, but I'm not sure how to translate this into proper python logic.

Basically what'd I'd like to do is

if file exists in any list_of_paths:
    print 'True'
else:
    print 'False'

Can anyone advise how to go about this?

Upvotes: 1

Views: 4149

Answers (4)

Chidi
Chidi

Reputation: 991

if you already have the folder names in a list and want to filter folders that have a particular file name in them, you can use a list comprehension thus:

import os
listOfFolders = [*contains the folderpaths*]
validFolders = [folder for folder in listOfFolders if 'badFile.txt' not in os.listdir(folder)]

this returns a list of folders that don't have badFile.txt in them. alternatively, you can omit the not if you want folders that have badFile.txt in them.

Upvotes: 1

Preston Garrison
Preston Garrison

Reputation: 103

Just replace where you call exists with os.path.exists(path), and your code should pretty much work.

Upvotes: 2

yole
yole

Reputation: 97168

One very simple solution is to wrap this code in a function that returns True as soon as it finds a path under which the file exists.

Upvotes: 2

jfs
jfs

Reputation: 414235

import os

print(any(os.path.exists(os.path.join(dirpath, filename))
          for directories in d.values()
          for dirpath in directories))

Upvotes: 4

Related Questions