解释器给出错误
TypeError: 'file' object has no attribute '__getitem__'
它告诉你file 类型不允许像f[0] 这样的索引等等。如果一个类型具有属性__getitem__,它允许索引,否则不允许。如果是文件,则为后者。
你可以通过做更多地了解文件。
>>> fileTest = open('fileName')
>>> type(fileTest)
<type 'file'>
>>> dir(fileTest)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
for 循环通常可以应用于任何可迭代的结构。
如果你想要一个行列表,那么你可以这样做。
>>> with open('fileName') as f:
lines = f.readlines()
或者通过做,
>>> with open('fileName') as f:
lines = [line for line in f]