由于某种原因,我无法测试我的功能。我收到了这个错误。
print(write_avg(out_file('grades.csv')))
Traceback (most recent call last):
Python Shell, prompt 3, line 1
builtins.NameError: name 'out_file' is not defined
任何人都可以帮我解决这个问题吗?这是我的功能。
def write_avg(L, out_file):
'''(list, file) -> NoneType
Given a list of lists where each inner list consists of a string and a
float,and an open file for writing, write the contents of each inner list
as a line in the file. Each line of the file should be the string followed
by the float separated by a comma. Close the file when done.
'''
for line in out_file:
L.append(',')
output_line = L
out_file.write(output_line)
out_file.close()
答案 0 :(得分:1)
def write_avg(L, out_file):
'''(list, file) -> NoneType
Given a list of lists where each inner list consists of a string and a
float,and an open file for writing, write the contents of each inner list
as a line in the file. Each line of the file should be the string followed
by the float separated by a comma. Close the file when done.
'''
open_out_file = open(out_file, 'w')
for y in L: # iterate over list
result = y[0]+','+str(y[1]) + '\n'
open_out_file.write(result) #format needed
return result
open_out_file.close()
gradeL = [['S',34],['A',34],['N',34],['L',34]]
write_avg(gradeL,'grades.csv')
Output in file:
S,34
A,34
N,34
L,34