[英]Reading file from one up directory in python2.7
I am trying to read file in a python script from one up level. 我正在尝试从一个更高级别的python脚本中读取文件。 My file structure is as below:
我的文件结构如下:
code
- scripts
-myscript.py
- .env
In .env I have my configs. 在.env中,我有我的配置。
And I am trying to read this file in myscript.py 我正在尝试在myscript.py中读取此文件
I did the below to read it: 我做了以下阅读:
envfile = open("../.env", "r")
Now when I run this python script from the scripts directory it works fine 现在,当我从scripts目录运行此python脚本时,它可以正常工作
This works good: 这很好用:
cd /var/www/html/code/scripts
python myscript.py
But if I do: 但是如果我这样做:
cd
python /var/www/html/code/scripts/myscript.py
Doesn't work and gives IOError: [Errno 2] No such file or directory: '../.env' 不起作用,并给出IOError:[Errno 2]没有这样的文件或目录:'../.env'
How can I make it to run if I pass the absolute or relative path in terminal? 如果在终端中通过绝对路径或相对路径,如何使其运行?
You can use pathlib2 : 您可以使用pathlib2 :
from pathlib import Path
path = Path(__file__).resolve().parents[1].joinpath(".env")
envfile = open(path)
import os
p = os.path.realpath(__file__)
envfile = open('/'.join(p.split('/')[:-1])+'/../.env')
also works 也可以
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.