Unable to open file in a folder directory with unknown suffix (Dynamic name)

269 Views Asked by At

I am trying to open a .html file in a directory which its suffix (the directory's) changes dynamically using Python. The suffix of its name is known - "Robustness", however, after it there's a date and time added to it, for example:

Robustnesss_10-03-2022_17_07_09

Robustnesss_10-03-2022_17_34_07

Robustnesss_12-03-2022_12_02_01

There's only one folder named Robustness_XX-XX-XX-XXXX-XX-XX-XX because its deleted after every search (after a build in Jenkins)

Is there a short way to call the directory with only prefix? I tried using an asterisk wildcard after Robustness:

HTMLFileToBeOpened = open(r"C:\Users\56789\Desktop\checks\folder\another_folder\CSV\Robustnesss*\summary.html", "r")

But it throws this error:

Traceback (most recent call last):
File "C:/Users/56789/Desktop/maim.py", line 4, in <module>
HTMLFileToBeOpened = open(r"C:\Users\56789\Desktop\checks\folder\another_folder\CSV\Robustnesss*\summary.html", "r")
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\\56789\\Desktop\\checks\\folder\\another_folder\\CSV\\Robustnesss*\\summary.html'

When I write the exact name of the folder(with date and time) it works correctly, but I cant use that.

1

There are 1 best solutions below

0
Edo Akse On

2 Simple options here. Note that both will throw an index error if the file or path doesn't exist. If you are not 100% sure that the file/path will exist, put it in a try .. except block.

Set the robust_start to the folder which contains the folder you're trying to access. In your example this would be C:\Users\56789\Desktop\checks\folder\another_folder\CSV

# shamelessly stolen from
# https://stackoverflow.com/a/43553807/9267296
import os


robust_start = "CSV"


robust_path = [os.path.join(dir, d) for dir, dirs, files in os.walk(robust_start) for d in dirs if "Robustness" in d][0]
print(robust_path)


robust_file = [os.path.join(dir, f) for dir, dirs, files in os.walk(robust_start) for f in files if f == "summary.html"][0]
print(robust_file)