如何解决Python:os.listdir OSError [Errno 5] 输入/输出错误:'tmp/json_folder'
问题:
我有一个文件夹(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 镜像作为 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>",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
问题:
提前致谢。
解决方法
您可以使用 os.scandir 或 glob.iglob。他们使用迭代器并避免在内存中加载整个列表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。