당신은 분할 중입니다 b1
단일 공간에서는 빈 값으로 이어질 수 있습니다.
>>> '88 89 '.split(' ')
['88', '', '89', '']
여기는 여분의 빈 줄입니다 int()
예외를 던지려면 :
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
사용 str.split()
~와 함께 아니요 대신 논쟁; 그런 다음 여분의 공백이 제거됩니다.
>>> '88 89 '.split()
['88', '89']
코드에 다른 문제가 있습니다. 잘 살펴보십시오.
def lab8():
userinput= "Lab8.txt"
lenoffile= len(userinput)
print "There is", lenoffile, "lines"
File= open (userinput, "r")
studentscores1= File.read()
studentlist= studentscores1.split("\n")
return studentlist, lenoffile
여기, lenoffile
~이다 ~ 아니다 파일의 줄 수. 문자 수입니다 'Lab8.txt'
; 두 값 모두 일어나다 되려고 8
, 그러나 해당 파일에서 일부 줄을 추가하거나 제거하면 나머지 코드에 대해 번호가 잘못됩니다.
이 숫자를 이름과 함께 유지하고 계산을 다시 작성하려면 작업을 수행해야합니다. 유지 함께 이름.
다음은 동일한 작업을 해결하기위한 대체 버전입니다.
outputfile = raw_input("What is the output filename? :")
with open('Lab8.txt') as infile, open(outputfile, 'w') as outtfile:
for name in infile:
scores = next(infile).split() # next() grabs the next line from infile here
scores = map(int, scores)
quiztotal = sum(scores[:4]) / 5
midtermtotal = sum(scores[5:7]) / 2
finaltotal = scores[7]
score = quiztotal * .3 + midtermtotal * .4 + finaltotal * .3
outfile.write(name)
outfile.write('{0:0.2f}\n'.format(score))