3

我试图调用模块,但由于某种原因它给了我错误。data.py 包含一个项目列表,在 main.py 中我试图迭代并打印这些项目。但我收到以下错误。

错误

Import error: No module named Basics

data.py 和 main.py 都位于 c:/python27/basics/

数据.py

bob={'name':'bobs mith','age':42,'salary':5000,'job':'software'}
sue={'name':'sue more','age':30,'salary':3000,'job':'hardware'}
people=[bob,sue]

主文件

from Basics import data

if __name__ == '__main__':
    for key in people:
        print(key, '=>\n  ', people[key])

如果我只提供导入数据,那么我会收到以下错误

名称错误:名称“人”未定义。

更新:

新代码:

from Basics import data

if __name__ == '__main__':

    for key in data.people:
        print(key, '=>\n  ', data.people[key])

TypeError:列表索引必须是整数,而不是字典

4

3 回答 3

5

You will need __init__.py in your Basics directory

And

you will need to have that directory in your PYTHON_PATH or sys.path

To use people you need to do either of these.

from Basics.data import people

Or

from Basics import data
print data.people
于 2012-06-01T21:15:24.550 回答
1

Did you make an __init__.py in c:/python27/basics/ ?

Also it is probably good practice to make the case of the import Basics match the case of the directory basics. It doesn't matter on windows I think, but it certainly will under unix.

于 2012-06-01T21:17:04.013 回答
1

对于第二部分,“people”对象是一个包含两个字典的列表。所以你想这样做:

for person in people:
  for key in person:
     print(key, '=>\n  ', person[key])
于 2012-06-02T11:12:59.283 回答