-1

I have used this to find a file in a given path:

path = "C:\\Users\\derpderp\\"
name = "derp.xlsx"

for root, dirs, files in os.walk(path):
    if name in files:
        print(name)

But how do one go about doing the inverse? So that if the file not exist: specify that file.

If I write:

if name not in files:
    print(name)

It will iterate the file name that not exist for every folder/file etc.

martineau
  • 119,623
  • 25
  • 170
  • 301
fr1234
  • 15
  • 3
  • Does this answer your question? [Excluding directories in os.walk](https://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk) – Phung Duy Phong Jan 14 '20 at 09:40
  • 1
    I don't understand what you are trying to do here. It feels like an XY problem (is `os.walk` actually the tool you should use?). Please explain in words what you are trying to achieve, what is your input and what output you expect – DeepSpace Jan 14 '20 at 09:42
  • I have an excel file with a list of filenames, I want to compare those filenames to a directory and subdirs. If a file from the list does not exist in any of the dirs, i want to print that filename. – fr1234 Jan 14 '20 at 12:38

2 Answers2

1

You could use pathlib's resolve() function and try/except for a FileNotFound error.

import pathlib

path = "C:\\Users\\derpderp\\"
name = "derp.xlsx"

try:
    file = pathlib.Path(path+name)
    file.resolve(strict=True)
except FileNotFoundError as e:
    print(name)

https://docs.python.org/3/library/pathlib.html

martineau
  • 119,623
  • 25
  • 170
  • 301
Ben Corcoran
  • 71
  • 1
  • 5
0

Although using the pathlib module as shown in @Ben Corcoran answer would probably the best (and fastest) way to do it, here's an alternative that uses the built-in any() function:

import os

def any_exists(filename, path):
    def gen_files(path):
        for root, dirs, files in os.walk(path):
            if filename in files:
                return filename
        return ()

    return any(gen_files(path))


path = "C:\\Users\\martineau"
name = "derp.xlsx"

if not any_exists(name, path):
    print(f'No file named {name} exists.')
else:
    print(f'A file named {name} exists.')
martineau
  • 119,623
  • 25
  • 170
  • 301