Python ImportError: 找不到名为'path'的模块

4
''' Data class'''

import os.path
from random import Random

class TestData(object, Random):

    def FetchDataFromFile(self, filename):
        """ Open the file as read only """
        myfile = open(os.path.join(os.getcwd(),filename), 'r')
        """ read the information in the file """
        lines = myfile.read()
        ''' Remove the header as this will not be used '''
        header = lines[0] 
        lines.remove(header)
        return lines

我遇到了以下问题:

导入错误: 找不到名为path的模块

在“pyclasspath/Lib/Testdata.py”文件的第2行,位于

在我的项目中,所有其他类都可以使用os.path。有人能告诉我我做错了什么吗?

我将这个文件从一个目录移动到了另一个目录。除此之外,这个类和其他类没有任何区别。


你可以使用 from os import path,但我认为更好的方式是 import os,然后在你的脚本中使用 os.path.method_name() - squiguy
@squiguy 如果他使用 from os import path,那么他需要使用 path 而不是 os.path - Tanky Woo
您那里有一个名为 os.py 的文件吗? - syntonym
2个回答

4

import os可以正常工作。

import os
from random import Random

class TestData(object, Random):

    def FetchDataFromFile(self, filename):
        """ Open the file as read only """
        myfile = open(os.path.join(os.getcwd(),filename), 'r')
        """ read the information in the file """
        lines = myfile.read()
        ''' Remove the header as this will not be used '''
        header = lines[0] 
        lines.remove(header)
        return lines

作为附注,你的方法可能是
def FetchDataFromFile(self, filename):
        """ Open the file as read only """
        return list(open(os.path.join(os.getcwd(),filename), 'r'))[1:]

1
恭喜你获得了10K声望。 - squiguy
好的。我找到了错误,目标文件夹的名称是“Lib”。我必须将它改为其他名称“Library”,然后它又开始工作了。谢谢你的建议。 - Loganswamy
但是 import os.path as op 是有效的。 - dashesy

2

在项目中,我将包名设置为'Lib'并将Testdata模块移动到了Lib中。我猜Python不喜欢这个包名。将其重命名为Library,现在它可以工作了。错误与导入语句无关。import os.path和from os import path都可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接