1

I am trying to figure out how to check (using preferably os module) if one directory contains another directory named "xyz". I have found this solutions: How to check if folder is empty with Python? yet I don't need to check if dir is empty or not, I need to check if dir has another dir and name must be correct ("xyz"). Also, I tried to find something in os documentation https://docs.python.org/3/library/os.html but I didn't come up with a solution.

Edyficjum
  • 81
  • 6

4 Answers4

2

TRY pathlib:

from pathlib import Path

inp_path =  Path('.') # specify the path in path constructor
dir_to_search = 'xyz'


def search_for_file(inp_path, dir_to_search):
    return any(
        file.is_dir() and file.name == dir_to_search
        for file in inp_path.glob('**/*')
    )

search_for_file(inp_path, dir_to_search) # this function will look for all the subdirectories.

HOW IT WORKS:

The above function uses glob to yield every file/directory in the path one by one, and then it's checking whether the file is a directory or not via file.is_dir. If it's, then extracts the name via file.name compares it with the dir_to_search. If the result is True - any function will detect it and return the value True else False.

Nk03
  • 14,699
  • 2
  • 8
  • 22
1

For every item (folder/file) in your path, it will check whether its name is xyz or not.

import os
path =r'C:\Users'
for path in os.listdir(path):
    if path=='xyz':
        print(True)
        break

Replace path with your current directory location.

ulti72
  • 79
  • 1
  • 9
0

you can do thst using os

file_path = "your directory"
import os
arr = list(map(lambda x: x.split('.')[0], os.listdir(file_path)))
# to cast: "file.text" to "file"
if 'xyz' in arr:
    ...
EyaS
  • 477
  • 3
  • 9
0

You can use os.walk(), replace "path of directory" below with... Well the path to directory you want to check

for dirname, subdir, filename in os.walk("path of directory"):
    if "xyz" in subdir:
        print("yes")
        break # to prevent unnecessarily checking more paths
else:
    print("no")

Note: This also checks sub directories

Muhd Mairaj
  • 557
  • 4
  • 13