文本文件未随模块导入

时间:2015-06-08 01:51:11

标签: python module

我正在开发一个项目,并具有以下目录结构:

Classifier_Code/
    classifier/
        __init__.py
        Event.py
        classifier.py
        lib/
            __init__.py
            categories.txt
    test.py

__init__.py内的文件lib/categories.txt中读取数百个类别名称的列表,并将它们存储在列表中,然后我要将其导入classifier.py声明

from lib import CATEGORY_LIST

然而,这样做时,我收到以下错误:

Traceback (most recent call last):
  File "classifier/classifier.py", line 1, in <module>
    from lib import CATEGORIES
  File "classifier/lib/__init__.py", line 3, in <module>
    with open('categories.txt') as categories:
IOError: [Errno 2] No such file or directory: 'categories.txt'

也就是说,当我尝试导入模块时,我收到错误,因为文本文件categories.txt随之而来。

是否有人知道针对此特定问题的修复方法?

2 个答案:

答案 0 :(得分:1)

如果您只是使用data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAF4AqsDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2gJt+XPJPUGv2A/NB2044oAdtY9M8ccCgB6r8+0jtSYDxEW4xz2qQFCnGOPQ0AAQDJIz9KAF8rI6/hQA9Y+SBgjHIqWA5Yxz2xUsBwUdAMdzSAcFGAB0NADgCVK/KB/OgB6BNzc49agse2OgX2BFZvcCRUO7g,那么它将在当前工作目录中查找文本文件。

如果您希望它查找open('categories.txt')所在的同一目录,请尝试将__init__.py更改为以下内容:

open

假设代码位于with open(os.path.join(os.path.dirname(__file__), 'categories.txt')) as categories: ,那么__init__.py应该是__file__的路径,并且您将以文本文件的完整路径结束。

答案 1 :(得分:1)

categories.txt将需要一个完整的路径,因此无法找到它的位置。 Python总是搜索当前目录。 尝试os.getcwd()获取当前的工作目录然后 尝试os.listdir()更改工作目录。这样您的文件将被识别。

此链接详细说明了Python如何处理文件导入及其工作原理: Importing files from different folder in Python