关于索引超出范围的Python3问题

时间:2018-07-26 06:17:03

标签: python-3.x

我遇到了这个问题。当我运行此代码时,使用上面的文件,它给了我索引超出范围的错误。

f = open(sys.argv[1], 'r')
file_contents = [x.split('\t')[2:5] for x in f.readlines()]
#Set the variables for average and total for cities

total = 0
city = set()
for line in file_contents:
     print(line[0])

这是文件的内容

2012-01-01  09:00   San Jose    Men's Clothing  214.05  Amex
2012-01-01  09:00   Fort Worth  Women's Clothing    153.57  Visa
2012-01-01  09:00   San Diego   Music   66.08   Cash
2012-01-01  09:00   Pittsburgh  Pet Supplies    493.51  Discover
2012-01-01  09:00   Omaha   Children's Clothing 235.63  MasterCard

1 个答案:

答案 0 :(得分:0)

您需要在读取文件后关闭文件,建议的做法是使用with语句将其自动关闭;

with open(sys.argv[1], 'r') as f:
    file_contents = [x.split(' ')[2:5] for x in f.readlines()]
    #Set the variables for average and total for cities

total = 0
city = set()
for line in file_contents:
     print(line[0])

但是,您遇到的问题是将行用\t分隔,请使用空格,它应该可以为您提供所需的内容。

  

输出

09:00
09:00
09:00
09:00
09:00