I'm writing a program that selects a random folder in a file and opens it. However, it works most of the time, but when it does not select a file, it crashes with the following error (here's the snippet of the code)...
File "C:\Users\rbloc\OneDrive\Documents\Thesis\Python Scripts\FileRO.py", line 51, in fileopener mystat = os.stat(randomFile)
builtins.FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
Here is the code:
def fileopener(logFile, StartTime, CloseTime):
#for loop through specified directory and copy append names of files into list
for root, dirs, files in os.walk(r"Y:\Documents\Data", topdown=True):
#time.sleep(randint(5,15))
for file in files:
file_list.append(os.path.join(root, file))
#select random file from the file list generated
randomFile = file_list[np.random.choice(len(file_list))]
I know the error is occurring on the last line, but I can't seem to fix it. Does anyone have a solution?
EDIT WITH NEW CODE:
So I removed the random function that caused the issue and just have the program open files using the for-loop and works great. So I've narrowed it down to the random function, as suspected, that is causing the program the crash when it does not select a file....
def fileopener(logFile, StartTime, CloseTime):
#for loop through specified directory and copy append names of files into list
for root, dirs, files in os.walk(r"Y:\Documents\Data", topdown=True):
#time.sleep(randint(5,15))
for file in files:
randomFile = os.path.join(root, file)
#print time stamp for operation that opened and open random file/folder selected
print("Time OPENED ", timeopen(), " file is: ", randomFile)