你可以像这样做:
你可以像这样做:
with open("data1.txt") as f:
lis = [line.split() for line in f]
for i, x in enumerate(lis):
print "line{0} = {1}".format(i, x)
line0 = ['Year:', 'Dec:', 'Jan:']
line1 = ['1', '50', '60']
line2 = ['2', '25', '50']
line3 = ['3', '30', '30']
line4 = ['4', '40', '20']
line5 = ['5', '10', '10']
或者:
with open("data1.txt") as f:
for i, line in enumerate(f):
print "line {0} = {1}".format(i, line.split())
line 0 = ['Year:', 'Dec:', 'Jan:']
line 1 = ['1', '50', '60']
line 2 = ['2', '25', '50']
line 3 = ['3', '30', '30']
line 4 = ['4', '40', '20']
line 5 = ['5', '10', '10']
编辑:
with open('data1.txt') as f:
print "{0}".format(f.readline().split())
for x in f:
x = x.split()
print "{0} = {1}".format(x[0],sum(map(int, x[1:])))
['Year:', 'Dec:', 'Jan:']
1 = 110
2 = 75
3 = 60
4 = 60
5 = 20
iterator should return strings, not bytes (did you open the file in text mode?)
,并通过将rb
更改为rt
来解决了它。 - J0ANMM