Edyficjum
Edyficjum

Reputation: 81

How to check if directory contains another directory named"xyz" in python?

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.

Upvotes: 1

Views: 2590

Answers (4)

Nk03
Nk03

Reputation: 14949

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.

Upvotes: 2

Muhd Mairaj
Muhd Mairaj

Reputation: 677

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

Upvotes: 0

ulti72
ulti72

Reputation: 79

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.

Upvotes: 1

EyaS
EyaS

Reputation: 606

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:
    ...

Upvotes: 0

Related Questions