在python项目中使用相对路径读取文件 [英] Reading file using relative path in python project

查看:4670
本文介绍了在python项目中使用相对路径读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个python项目,其结构如下:

Say I have a python project that is structured as follows:

project
    /data
        test.csv
    /package
        __init__.py
        module.py
    main.py

__ init __。py

from .module import test

module.py

import csv

with open("..data/test.csv") as f:
    test = [line for line in csv.reader(f)]

main.py

import package

print(package.test)

当我运行 main.py 我收到以下错误:

When I run main.py I get the following error:

 C:\Users\Patrick\Desktop\project>python main.py
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import package
  File "C:\Users\Patrick\Desktop\project\package\__init__.py", line 1, in <module>
    from .module import test
  File "C:\Users\Patrick\Desktop\project\package\module.py", line 3, in <module>
    with open("../data/test.csv") as f:
FileNotFoundError: [Errno 2] No such file or directory: '../data/test.csv'

但是,如果我从<运行 module.py code> package 目录我没有错误。因此,似乎 open(...)中使用的相对路径仅相对于运行原始文件的位置(即 __ name__ = =__ main __)?我不想使用绝对路径。有什么方法可以解决这个问题?

However, if I run module.py from the package directory I get no errors. So it seems that the relative path used in open(...) is only relative to where the originating file is being run from (i.e __name__ == "__main__")? I don't want to use absolute paths. What are some ways to deal with this?

推荐答案

相对路径是相对于当前工作目录
如果你不想要你的路径,它必须是绝对的。

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.

但是有一个常用的技巧来构建当前脚本的绝对路径:使用其 __ file __ 特殊属性:

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))

注意,来自python 3.4 , __ file __ 对于导入的模块始终是绝对的,您可以在此示例中删除 os.path.abspath 部分。并不是说它是绝对必要的,但是如果你在某个时候改变当前的工作目录而你的模块是用相对路径导入的,那就避免了意外。

Note, from python 3.4, __file__ is always absolute for imported modules and you can drop the os.path.abspath part in this example. Not that it is strictly necessary, but it avoids surprises if you change the current working directory at some point and your module was imported using a relative path.

这篇关于在python项目中使用相对路径读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆