相对路径中没有这样的文件或目录[英] No such file or directory for relative path

本文是小编为大家收集整理的关于相对路径中没有这样的文件或目录的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我在一个python文件中有一个瓶子应用-Backend.py.该文件包含以下定义:

variable = {
    'field': [f for f in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')]
}

def run_fcgi():
    from bottle import FlupFCGIServer
    run(port=8080, server=FlupFCGIServer)

if __name__ == "__main__":
    run(host='0.0.0.0', port=8087, server='waitress')

当我运行此应用时,例如:

python backend.py

成功启动了应用程序.

当我将此应用程序作为FCGI应用程序(fcgi.py)运行时:

#!my_path_to_python

if __name__ == '__main__':
    import backend
    backend.run_fcgi()

我有一个错误:

Traceback (most recent call last):
  File "path_to_my_project/fcgi.py", line 9, in <module>
    import backend
  File "path_to_my_project/backend.py", line 49, in <module>
    'msk': [i for i in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')],
IOError: [Errno 2] No such file or directory: '../data/fields.csv'

有什么想法?

推荐答案

我认为最好不要依靠工作目录.并使用相对于使用此路径的文件的路径.我的意思是您可以即时计算路径:

import os
csv_path = '../data/fields.csv'
csv_path = os.path.join(os.path.dirname(__file__), csv_path)

在这种情况下,人们可以在不同的环境上运行您的脚本.完整的路径将用于确保您不依赖工作目录.

本文地址:https://www.itbaoku.cn/post/1975376.html

问题描述

I have a bottle application in one python file - backend.py. The file contains these definitions:

variable = {
    'field': [f for f in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')]
}

def run_fcgi():
    from bottle import FlupFCGIServer
    run(port=8080, server=FlupFCGIServer)

if __name__ == "__main__":
    run(host='0.0.0.0', port=8087, server='waitress')

When I run this app like:

python backend.py

application is started successfully.

When I run this application as fcgi application (fcgi.py) by supervisor:

#!my_path_to_python

if __name__ == '__main__':
    import backend
    backend.run_fcgi()

I have an error:

Traceback (most recent call last):
  File "path_to_my_project/fcgi.py", line 9, in <module>
    import backend
  File "path_to_my_project/backend.py", line 49, in <module>
    'msk': [i for i in csv.DictReader(open('../data/fields.csv', 'rb'), delimiter=';')],
IOError: [Errno 2] No such file or directory: '../data/fields.csv'

Any ideas?

推荐答案

I think It's better not to rely on working directory. and use path relative to file that is uses this path. I mean you can calculate path on the fly:

import os
csv_path = '../data/fields.csv'
csv_path = os.path.join(os.path.dirname(__file__), csv_path)

In this case one be able to run your script on different environment. an full path will be used to be sure that You don't depends on working directory.