python3本地文件的包路径

标签 python python-3.x python-import python-packaging

我有以下结构

/
/myPackage/
          __init__.py
          myFile.csv
          myFunc.py
/test/
     __init__.py
     func.py

现在 myfunc.py 有一个读取 myFile.csv 的函数

def foo():
     with open('myFile.csv', newline='') as csvfile:
     ......

如果我在 func.py 中导入 foo,则路径“myFile.csv”不再正确。 如何从 myFunc.py 引用 myFile.csv 而不依赖于导入 myfunc 的文件?

最佳答案

您可以使用__file__指当前模块的文件路径;将 __file__os.path.dirname 结合起来,您可以获取包含该模块的目录。

import os

def foo():
     directory = os.path.dirname(__file__)
     csv_path = os.path.join(directory, 'myFile.csv')
     with open(csv_path, newline='') as csvfile:
         ...

如果您使用Python 3.4+,则可以使用pathlib相反:

import pathlib

def foo():
     csv_path = pathlib.Path(__file__).parent / 'myFile.csv'
     with csv_path.open(newline='') as csvfile:
         ...

关于python3本地文件的包路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513588/

相关文章:

python - 如何检查 Python 字典中存在的相同键

python - 为字符的矩形矩阵添加边框(*)

python - 如何在这个类中通过python创建一个链表

python - os.path.join 不存在的假路径总是可以吗?

python - 如何对整数列表的一部分进行排序?

python - python中的导入是否被认为是动态链接?

python - 从 __init__ 中的 Python 子模块导入方法,但不是子模块本身

python-3.x - 模块 'urllib' 没有属性 'request'

python - 分散 DataFrame 的快速插值

python - 如何根据另一列更改数据框列中的值?