在Colab运行Geogramint时遭遇No such file or directory问题求助
问题:Colab中运行Geogramint时无法定位appfiles/config.ini文件
在Colab中克隆Geogramint仓库后,按常规路径调整运行代码,出现文件找不到错误:
FileNotFoundError: [Errno 2] No such file or directory: 'appfiles/config.ini'
克隆与运行的代码对比
GitHub原代码:
git clone https://github.com/Alb-310/Geogramint.git cd Geogramint/ pip install -r requirements.txt python geogramint.py # for GUI mode python geogramint.py --help # for CLI mode
Colab中使用的代码:
!git clone https://github.com/Alb-310/Geogramint.git !cd Geogramint/ !pip install -r Geogramint/requirements.txt !python3 Geogramint/geogramint.py --help # for CLI mode
错误根源
问题出在settings_cli.py第44行的相对路径:
with open('appfiles/config.ini', 'w') as configfile:
程序以Colab默认工作目录/content为基准寻找文件,但实际文件路径为/content/Geogramint/appfiles/config.ini,导致路径不匹配。
解决方案
方法1:切换工作目录后运行代码
Colab中单个!命令是独立shell会话,单独!cd无法改变后续命令的工作目录,需用%cd魔法命令或串联命令:
!git clone https://github.com/Alb-310/Geogramint.git %cd Geogramint/ !pip install -r requirements.txt !python3 geogramint.py --help
或用单条shell命令串联执行:
!git clone https://github.com/Alb-310/Geogramint.git && cd Geogramint && pip install -r requirements.txt && python3 geogramint.py --help
方法2:修改代码路径为基于脚本位置的绝对路径
打开/content/Geogramint/CLI/settings_cli.py,修改路径逻辑,让程序基于脚本所在目录定位文件:
# 先导入os模块(如果文件顶部没导入) import os # 获取当前脚本的绝对目录 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接config.ini的完整路径 config_path = os.path.join(script_dir, '../appfiles/config.ini') # 替换原open语句 with open(config_path, 'w') as configfile:
修改后无论从哪个目录运行,程序都能准确定位文件。
方法3:创建软链接(临时应急方案)
在/content目录下创建指向目标文件夹的软链接,让程序的相对路径指向正确位置:
!ln -s Geogramint/appfiles appfiles
注意:此方案为临时解决,Colab重启后需重新创建链接。
内容的提问来源于stack exchange,提问作者Kemal Yıldırım
相关产品推荐
相关产品推荐

