我遇到了这个问题。当我运行此代码时,使用上面的文件,它给了我索引超出范围的错误。
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
答案 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