python os listdir 列出错误目录的文件

问题描述 投票:0回答:1

os.listdir 是否缓存其结果或类似的内容?它为我列出了以前文件夹中的文件。

我制作了一个相当简单的程序,只是为了测试读取文件的并行处理,它获取一个文件夹,列出文件夹中的所有文件,读取内容并将它们放入列表中:

from tqdm import tqdm #Just prints a pretty progressbar
from multiprocessing import Pool
from os import listdir

folder = 'dungeon/' #previously folder = 'buff/'

def read_file(file):
    with open(folder+file,'rb') as f:
        return f.read()

def read_parallel(files):
    with Pool() as p:
        l = list(tqdm(p.imap(read_file, files), total=len(files)))
    return l
    

def main():
    files = listdir(folder)
    l = read_parallel(files)

目录结构是这样的:

script.py
dungeon
->dungeon_1.lua
->dungeon_2.lua etc.
buff
->buff_1.lua
->buff_2.lua etc.

我用

folder = 'buff/'
运行了这个,它执行时没有问题。

然后我再次运行它,但将行更改为

folder = 'dungeon/'
并收到错误
FileNotFoundError: [Errno 2] No such file or directory: '../Src/EN/gamecfg/dungeon/buff_1.lua'
,在
open(folder.file, 'rb')
部分引发。这并不奇怪,因为该文件不存在,它只出现在 buff 目录中。

然后我再次运行它,没有进行任何更改,它就成功了。

我只是不明白为什么会发生这种情况,我想知道在此之后我是否仍然可以信任 listdir 。 (也请随时告诉我这是否是快速读取许多小文件的不好方法。)

python listdir filenotfounderror
1个回答
0
投票

您可以使用

os.path.join
来实现更好的路径处理:以下是更新的代码。

def read_file(file):
    file_path = os.path.join(folder, file)
    with open(file_path, 'rb') as f:
        return f.read()
def main():
    files = os.listdir(folder)
    l = read_parallel(files)
© www.soinside.com 2019 - 2024. All rights reserved.