【问题标题】:Python: os.listdir OSError [Errno 5] Input/output error: 'tmp/json_folder'Python:os.listdir OSError [Errno 5] 输入/输出错误:'tmp/json_folder'
【发布时间】:2021-03-22 14:12:17
【问题描述】:

问题:

我有一个文件夹 (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

环境:

上面的问题是 docker image 作为 pycharm 解释器

当解释器是conda env时,没有错误

我可以看到的唯一区别是,在我的 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 env 下没有引发错误

提前致谢。

【问题讨论】:

  • 嗯。你试过os.listdir("/tmp/json_folder_large")?
  • 嗨,@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'
  • 这能回答你的问题吗? IOError: [Errno 5] Input/output error

标签: python bash docker operating-system oserror


【解决方案1】:

您可以使用os.scandirglob.iglob。他们利用迭代器并避免将整个列表加载到内存中。

【讨论】:

  • 我刚刚尝试使用 pathlib 中的 os.scandirPath,在我的情况下没有任何效果,我将把它更新到我的问题中
  • 你的意思是你在使用 os.scandir 时也遇到了 i/o 错误?
  • 嗨@llllrnr101 我用 os.scandir 更新了该部分,当我迭代生成器时它会引发错误
  • 那我觉得内存不是你的问题。我会放一个 sleep(60) 然后将进程附加到 strace 看看我是否得到任何线索。
  • 是否使用模式调用 scnadir 或 listdir 也会给您错误。就像尝试从该目录中仅获取一组文件一样?
猜你喜欢
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 2023-03-15
  • 2019-09-21
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2021-04-10
相关资源
最近更新 更多