【发布时间】:2014-11-03 23:13:43
【问题描述】:
所以在 Python 命令行中:
th = {u'category': u'Hair Color'}
>>> print q
{u'category': u'Hair Color'}
>>> print th['category']
Hair Color
这很好。但现在假设我有一个名为 ant.txt 的文件,其内容相同:
{u'category': u'Hair Color'}
我又想像上面一样打印对象和成员。
>>> f = open('ant.txt')
>>> q = f.read()
>>> print q
{u'category': u'Hair Color'}
>>> print q['category']
Traceback (most recent call last):
File "<pyshell#230>", line 1, in <module>
print q['category']
TypeError: string indices must be integers, not str
我知道错误的原因是我没有指定整数。但是为什么我从文件加载而不是在命令行创建时会出现错误?
从文件读取时我需要将什么更改为print q['category']?
【问题讨论】:
标签: python file dictionary