Python:os.listdir OSError [Errno 5] 输入/输出错误: 'tmp/json_folder'

5

问题:

我有一个文件夹(json_folder_large),里面有超过200,000个json文件,另外一个文件夹(json_folder_small)里有10,000个json文件。

import os
lst_file = os.listdir("tmp/json_folder_large") # this returns an OSError
OSError: [Errno 5] Input/output error: 'tmp/json_folder_large'

当我使用文件夹路径的listdir时,出现了OSError。我确定路径没有问题,因为我可以在其他文件夹中执行相同的操作而没有这个OSError。

lst_file = os.listdir("tmp/json_folder_small") # no error with this

环境:

以上问题涉及到使用PyCharm解释器的Docker镜像

当解释器为conda环境时,没有错误

我唯一看到的区别是,在我的docker/preferences/resources/advanced中,我设置了4个CPU(最大值为6)和32GB内存(最大值为64)。

我尝试过:(在docker下)

1. 使用 Pathlib

import pathlib
pathlib.Path('tmp/json_folder_large').iterdir() # this returns a generator <generator object Path.iterdir at 0x7fae4df499a8>
for x in pathlib.Path('tmp/json_folder_large').iterdir():
    print("hi")
    break

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/local/lib/python3.7/pathlib.py", line 1074, in iterdir for name in self._accessor.listdir(self):
OSError: [Errno 5] Input/output error: 'tmp/json_folder_large'

2. 使用 os.scandir

os.scandir("tmp/json_folder_large") # this returns a generator <posix.ScandirIterator object at 0x7fae4c48f510>
for x in os.scandir("tmp/json_folder_large"):
    print("hi")
    break
Traceback (most recent call last):
  File "<input>", line 1, in <module>
OSError: [Errno 5] Input/output error: 'tmp/json_folder_large'

3.连接PyCharm终端到Docker容器,然后执行ls命令。

docker exec -it 21aa095da3b0 bash
cd json_folder_large
ls

然后我遇到了一个错误(当终端不与Docker容器连接时,上面的代码没有产生错误!!!

ls: reading directory '.': Input/output error

问题:

  1. 是否真的是因为内存问题?
  2. 相同目录下一切都在的情况下,是否有可能解决此错误?(我看到我们可以将这些文件拆分到不同的目录中)
  3. 为什么我的代码在docker环境下会引发错误,但在conda环境下却不会

提前致谢。


你试过使用os.listdir("/tmp/json_folder_large")吗? - mutantkeyboard
1
嗨,@mutantkeyboard,我确定路径应该是'tmp/json_folder_large',如果我执行 os.listdir("/tmp/json_folder_large"),我会得到一个 FileNotFoundError: [Errno 2] No such file or directory: '/tmp/json_folder_large' 错误。顺便说一下,我的当前工作目录是 '/opt/project' - Mapotofu
这个回答解决了你的问题吗?IOError:[Errno 5]输入/输出错误 - Maurice Meyer
1个回答

0
你可以使用 os.scandir 或者 glob.iglob。它们利用迭代器避免在内存中加载整个列表。

我刚刚尝试了使用 os.scandir 和来自 pathlib 的 Path ,但对我的情况都不起作用,我会将此更新到我的问题中。 - Mapotofu
你是说使用os.scandir时也遇到了I/O错误? - lllrnr101
嗨@lllrnr101,我更新了使用os.scandir的部分,但当我遍历生成器时,它会引发错误。 - Mapotofu
那么我认为内存不是你的问题。我会放一个sleep(60),然后将进程附加到strace上,看看是否能得到任何线索。 - lllrnr101
使用带有模式的scnadir或listdir调用是否也会给您带来错误?例如,尝试仅从该目录获取文件的子集? - lllrnr101
我没有添加任何模式,但如果是由于这些原因引起的,那么我无法解释为什么它在 conda 环境 下工作,唯一出现此错误的情况是在 docker 下。 - Mapotofu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接