当我尝试在我的 python 程序中打开一个文件时,即使它们位于同一目录中,我也会遇到一个奇怪的错误。这是我的代码:
def main():
#filename = input("Enter the name of the file of grades: ")
file = open("g.py", "r")
for line in file:
points = 0
array = line.split()
if array[1] == 'A':
points = array[2] * 4
elif array[1] == 'B':
points = array[2] * 3
elif array[1] == 'C':
points = array[2] * 2
elif array[1] == 'D':
points = array[2] * 1
totalpoints += points
totalpointspossible += array[2]*4
gpa = (totalpoints/totalpointspossible)*4
print("The GPA is ", gpa)
file.close()
main()
这是我得到的错误:
Traceback (most recent call last):
File "yotam2.py", line 51, in <module>
main()
File "yotam2.py", line 28, in main
file = open(g.py, "r")
NameError: global name 'g' is not defined
我不太确定为什么它说 g 未定义,即使它与我的 python 文件位于同一目录中。