當我嘗試在我的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