def parse_to_number(var):
try:
return int(var)
except ValueError:
return 0
inputFile = open("Students_1.txt" , 'w')
inputFile.write("John Smith 80 90\n")
inputFile.write("Ryan Brown 80 60\n")
inputFile.write("Anna Myers 95 85\n")
inputFile.close()
inputFile = open("Students_1.txt" , 'r')
for line in inputFile:
y = line.split()
first_name = y[0]
last_name = y[1]
math_grade = parse_to_number(y[2])
chem_grade = parse_to_number(y[3])
ave = (math_grade + chem_grade)/2.0
print(math_grade, chem_grade, ave)
我试图让最终结果看起来像一个列表,但只是将平均值添加到结尾,所以它显示三组不同的数字而不是两组这样的数字,但将其保存到标题为&#的输出文件中34; Students_2.txt"请帮忙!!!
John Smith 80 90 85.0 瑞安布朗80 60 70.0 安娜迈尔斯95 85 90.0
答案 0 :(得分:1)
您应该使用上下文管理器打开文件 - 请注意您不需要显式关闭它。
with open("Students_1.txt" , 'w') as input_file:
input_file.write("John Smith 80 90\n")
input_file.write("Ryan Brown 80 60\n")
input_file.write("Anna Myers 95 85\n")
您可以在一行中打开输入文件和输出文件,例如
with open("Students_1.txt" , 'r') as input_file, open("Students_2.txt" , 'w') as output_file:
for line in input_file:
y = line.split()
first_name = y[0]
last_name = y[1]
math_grade = parse_to_number(y[2])
chem_grade = parse_to_number(y[3])
ave = (math_grade + chem_grade) / 2.0
print(*y, ave, file=output_file)
将路径存储在变量中是个好主意。还要将代码分解为某些函数。