从python蛋访问文件

2024-06-01 10:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我在python打包工作。我有3个non-code文件,即['synonyms.csv', 'acronyms.csv', 'words.txt']。在

  • 这些文件存在于文件夹结构Wordproject/WordProject/Repository/DataBank/
  • 我有一个RepositoryReader类,路径是Wordproject/WordProject/Repository/
  • 我编写了一个代码,它提取了RepositoryReader的当前位置,然后查找名为DataBanksubdirectory,并在那里查找3个文件。在

问题是当我从代码中创建一个egg,然后运行它时

我的代码显示错误:

Could not find the file at X:\1. Projects\Python\Wordproject\venv\lib\site-packages\Wordproject-1.0-py3.6.egg\Wordproject\Repository\DataBank\synonyms.csv

如果路径是一个鸡蛋,它将无法从路径中获取或读取文件。有什么办法吗?这些文件必须在egg中。在


Tags: 文件csv代码路径eggrepositorycodesynonyms
3条回答

基于documentation,我们可以用多种方式读取文件的内容。在

解决方案1:直接将文件内容读入内存。

不在本地提取文件。在

import zipfile, tempfile
tfile = tempfile.NamedTemporaryFile()
with zipfile.ZipFile('/path/to/egg.egg') as myzip:
    with myzip.open('relative/path/to/file.txt') as myfile:
        tfile.write(myfile.read())

# .. do something with temporary file

tfile.close()

现在,tfile是您的本地临时文件句柄。它的名称是tfile.name,所有的文件操作,如open(tfile)等,在这方面工作正常。tfile.close()必须在末尾调用以关闭句柄。在

文件的内容可以由myfile.read()本身读取,但一旦退出上下文,就会丢失myfile句柄。所以,如果需要为其他操作传递文件,则会将文件的内容复制到临时文件中。在

溶液2:局部提取卵子成员

zipfile提供用于提取特定成员的API

^{pr2}$

溶液3:提取整个鸡蛋

另一种解决方案是提取临时文件夹中的egg,然后读取该文件。可以在命令行上提取Egg,如下所示

python -m zipfile -e path/to/my.egg ./temp_destination

egg文件只是重命名为.zip文件。在

您可以使用^{}库打开egg并提取或读取所需的文件。在

import zipfile

zip = zipfile.ZipFile('/path/to/file.egg', 'r')

# open file from within the egg
f = zip.open('synonyms.csv', 'r')
txt = f.read()

您可以尝试在这里做两件不同的事情:

  • 将数据文件视为包的一部分,就像Python模块一样,并在运行时访问它们,就好像您的包是一个普通的目录树一样,即使它不是
  • pip install时间将安装在其他地方的数据文件放到一个您可以正常访问的位置。在

在PyPA/setuptools文档的the section on data files中都有解释。我想你想要第一个,这在Accessing Data Files at Runtime小节中有介绍:

Typically, existing programs manipulate a package’s __file__ attribute in order to find the location of data files. However, this manipulation isn’t compatible with PEP 302-based import hooks, including importing from zip files and Python Eggs. It is strongly recommended that, if you are using data files, you should use the ResourceManager API of pkg_resources to access them. The pkg_resources module is distributed as part of setuptools, so if you’re using setuptools to distribute your package, there is no reason not to use its resource management API. See also Accessing Package Resources for a quick example of converting code that uses __file__ to use pkg_resources instead.

沿着这个链接,你会发现一些看起来像是粗糙的旧PEAK文档,但那只是因为它们确实是粗糙的旧PEAK文档。有一个version buried inside the ^{} docs,一旦你设法找到它,你会发现它更容易阅读和导航。在

正如它所说的,您可以使用get_data(它在egg/zip中工作),然后返回到访问文件(从源代码运行时可以工作),但是最好使用pkg_resources中的包装器。基本上,如果您的代码是这样做的:

path = os.path.join(__file__, 'Wordproject/WordProject/Repository/DataBank/', datathingy)
with open(path) as f:
    for line in f:
        do_stuff(line)

…将其更改为:

^{pr2}$

请注意,resource_stream文件总是以二进制模式打开的。所以如果你想把它们当作文本来读,你需要在它们周围加上TextIOWrapper,或者对每一行进行解码。在

相关问题 更多 >