口译员给出了错误
TypeError: 'file' object has no attribute '__getitem__'它告诉您file类型不允许像f[0]那样建立索引,依此类推。如果类型具有属性__getitem__,则它允许索引,否则不允许。在文件的情况下,它是后者。
您可以通过操作了解有关文件的更多信息
>>> fileTest = open('fileName')
>>> type(fileTest)
>>> 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]