如何获取包内文件的内容

问题描述 投票:0回答:1

我正在用Python编写一些内容,我希望使用包中文件的预定义文本。不知何故,我无法让它在Eclipse PyDev控制台中运行。

filepath

这是我的路径结构。从“story.py”我想使用“starttext”的内容。

我尝试使用os.getcwd()和os.path.dirname(sys.argv [0])的多种变体的open(),

FileNotFoundError:[Errno 2]没有这样的文件或目录:'.. \ starttext'

我最后的尝试是尝试类似的东西

import pkg_resources
resource_package = __name__
resource_path = '/'.join(('.', 'starttext'))
template = pkg_resources.resource_stream(resource_package, resource_path)

导致:

 Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python\Python36-64\lib\site-packages\pkg_resources\__init__.py", line 1232, in resource_stream
    self, resource_name
  File "C:\Program Files\Python\Python36-64\lib\site-packages\pkg_resources\__init__.py", line 1479, in get_resource_stream
    return io.BytesIO(self.get_resource_string(manager, resource_name))
  File "C:\Program Files\Python\Python36-64\lib\site-packages\pkg_resources\__init__.py", line 1482, in get_resource_string
    return self._get(self._fn(self.module_path, resource_name))
  File "C:\Program Files\Python\Python36-64\lib\site-packages\pkg_resources\__init__.py", line 1560, in _get
    "Can't perform this operation for loaders without 'get_data()'"
NotImplementedError: Can't perform this operation for loaders without 'get_data()'

这似乎与python 3.x有关?

这似乎是一件容易的事,我不明白什么是错的。任何帮助表示赞赏。

谢谢。

更新

感谢ShmulikA我改为:

    from os.path import dirname, join, abspath
    filename = join(dirname(abspath(communitybot.anthology.teststory.story.__file__)), 'starttext')
    file = open(filename, 'r')

    content = file.read()

虽然我认为它有点长,但我确信我仍然在那里做错了。

python eclipse python-3.6
1个回答
1
投票

好像你错过了\ - 使用os.path.join

from os.path import dirname, join, abspath
filename = join(dirname(abspath(__file__)), 'starttext')
file = open(filename, 'r')
  • __file__ - 模块源文件的路径(你也可以导入requests;requests.__file__
  • os.path.abspath - 返回绝对文件名(例如abspath('..')返回/home
  • os.path.dirname - 返回文件的dirname
  • os.path.join - 加入兼容linux和windows的文件部分
© www.soinside.com 2019 - 2024. All rights reserved.