Skip to main content
 首页 » 编程设计

python之如何使用 open() 使用相对路径在 python 中打开文件

2025年05月04日15Free-Thinker

<分区>

我试图不为我的配置文件使用绝对路径,因为我需要在多个环境中部署它,我最好的选择是什么

下面的代码是我尝试过的,它无法找到路径,但是我可以将文件放在同一位置。我在 Redhat 服务器上使用 Python3.6。

with open("~/scripts/config.yml", 'r') as ymlfile: 
    cfg = yaml.load(ymlfile) 

我收到以下错误:

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
FileNotFoundError: [Errno 2] No such file or directory: '~/scripts/config.yml'