![](/img/trans.png)
[英]How to use Relative paths in python with, "with open()" and windows cmd or powershell
[英]how to use relative paths instead of full paths in windows using python
我想知道如何在 python 中使用相对路径而不是完整路径。 在 Linux 中它没问题,但是在 Windows 中,当我尝试使用./
来指示相对路径时,它会向我抛出一个错误,指出FileNotFoundError: [Errno 2] No such file or directory: 'C:\\\\Users\\\\Ender_Bender\\\\page\\\\index.html'
。 这是我的代码:
from flask import Flask
from os.path import abspath
app = Flask(__name__)
htmlCode = open(abspath('./page/index.html'),'r')
@app.route("/")
def index():
return f"""
{htmlCode}
"""
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
我该如何解决?
以下应该工作:
from os.path import abspath
import os
dirpath = os.path.dirname(os.path.realpath(__file__))
print (dirpath + "\n")
path = os.path.join(dirpath, 'page/index.html')
print (path + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.