当我尝试在我的python程序中打开文件时,即使它们位于同一目录中,我也会遇到一个奇怪的错误。这里是我的代码:在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文件。
您可能需要修复代码中的空白。它看起来像你还有一些未定义的变量? – 2013-05-02 07:02:25