Home > OS >  Get particular folder from directory
Get particular folder from directory

Time:10-12

I'm trying to get a specific sub-folder, such as "b," from the test/foo1 folder in the image below. I'm attempting to do this dynamically so that no hardcoded names appear within the code. enter image description here

so what I have achieved till now That I am able to get all the folders inside the test folder"a,b,c,d", but I dont know how to get any one particular folder dynamically

 list=[]
subfolders_lst = [f.name for f in os.scandir(c:test/foo1) if f.is_dir()]
    for subfolder_str in subfolders_lst:
        if subfolder_str in list:
            test_list = [f.name for f in os.scandir(os.path.join(self_test,subfolder_str)) if f.is_dir()]

CodePudding user response:

You can use input() to not "hard code" a folder to search for, but then you need to provide user-input.

You don't need to scan, either. Just test its existence.

import os

folder_name = input('Enter folder name: ')
look_for = os.path.join('c:\\', 'test', 'foo1', folder_name)
if os.path.isdir(look_for):
  print(f'Found: {look_for}')
else:
  print(f'Did not find {folder_name}')

CodePudding user response:

As per comments on the previous answer:

import os
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--module', help='Folder Name')
args = parser.parse_args()
folder_name = args.module
look_for = os.path.join('c:\\', 'test', 'foo1', folder_name)
if os.path.isdir(look_for):
  print(f'Found: {look_for}')
else:
  print(f'Did not find {folder_name}')
  • Related