随机文件打开器有时不能打开文件并崩溃。

11 浏览
0 Comments

随机文件打开器有时不能打开文件并崩溃。

我正在编写一个程序,它可以选择一个随机文件夹并打开它。然而,它大多数时间都可以工作,但是当它无法选择文件时,它会崩溃,并显示以下错误(这是代码段)...

File \"C:\\ Users \\ rbloc \\ OneDrive \\ Documents \\ Thesis \\ Python Scripts \\ FileRO.py\",第51行,在fileopener中

mystat = os.stat(randomFile)

builtins.FileNotFoundError:[WinError 3]系统找不到指定的路径:\'\'

这里是代码:

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))]

我知道错误发生在最后一行,但我似乎无法解决它。有人有解决方案吗?

用新代码编辑:

因此,我删除了引起问题的随机函数,只使用for循环打开文件,它工作很好。因此,我已经将问题缩小到了随机函数,就像我怀疑的那样,它在无法选择文件时导致程序崩溃....

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)

admin 更改状态以发布 2023年5月25日
0
0 Comments

这段代码对我有效

import os
import numpy as np
def fileopener(logFile, StartTime, CloseTime):
    file_list = []
    #for loop through specified directory and copy append names of files into list
    for root, dirs, files in os.walk("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))]
    print(randomFile)

0