-1

I am trying to create a file into the right directory based on a 4 digit int. Example: I'm creating an excel file and I want it to be placed into a folder that contains 1234 somewhere in the name like "Folder(1234)_do. I have the parent directory but it contains a large amount of subdirectories.

I imagine that I could use pathlib and regex maybe but can't really get it to work.

My code:

root_dir = '/Users/user/Desktop/Projects/'
path_list = []
for path in Path(root_dir).iterdir():
    if path.is_dir():
         path_list.append(path)
print(path_list)

i = str(2244)
result = any(i in string for string in str(path_list))

print(result)

I don't really know how I can search path objects and I'm not really sure where to start to solve this.

Any help or suggestions are highly appreciated

Syed Ahmad
  • 82
  • 3
G_olof
  • 31
  • 6

2 Answers2

1

The below should work and return folders that contains '2244'

from pathlib import Path

root_dir = '/Users/user/Desktop/Projects/'
i = str(2244)
path_list = [path for path in Path(root_dir).iterdir() if path.is_dir() and i in path]
print(path_list)
balderman
  • 22,927
  • 7
  • 34
  • 52
0

I found what I was looking for, maybe someone else could gain as well.

import glob

i = 1234

path_found = glob.glob('/Users/user/Desktop/Projects/*{i}*'.format(i=i))
G_olof
  • 31
  • 6