You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm中指定目录实际存在却触发[Errno 2] No such file or directory错误的求助

PyCharm中指定目录实际存在却触发[Errno 2] No such file or directory错误的求助

各位大佬好,我现在碰到一个特别奇怪的问题:我想把Oasis_3_3D目录下的所有子文件夹名称写入到txt文件里,但脚本一直提示找不到指定的目录,可这个目录明明实实在在存在于我的项目文件中。

以下是我写的代码:

import os

start_path = '~/MLMI/m3ae/Oasis_3_3D'

if os.path.exists(start_path) and os.path.isdir(start_path):
    folder_names = [d for d in os.listdir(start_path) if os.path.isdir(os.path.join(start_path, d))]
    with open('folder_list.txt', 'w') as f:
        for folder in folder_names:
            f.write("%s\n" % folder)
    print('Folders have been written to folder_list.txt.')
else:
    print(f"The directory {start_path} does not exist.")

运行这段代码后,输出结果是:

The directory ~/MLMI/m3ae/Oasis_3_3D does not exist.

如果我去掉存在性检查的if语句,直接执行os.listdir()相关代码,就会抛出错误:

[Errno 2] No such file or directory

但我反复确认过,这个目录确实在我的项目文件夹里,有没有人能帮我看看问题出在哪?

备注:内容来源于stack exchange,提问作者Nathan Huang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:04:35