2013-05-02 134 views
0

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

+0

您可能需要修復代碼中的空白。它看起來像你還有一些未定義的變量? – 2013-05-02 07:02:25

回答

5

g.py應該是一個字符串:

file = open("g.py", "r") 

此外,array是字符串列表。乘以整數字符串只是複製他們:

>>> "1" * 4 
"1111" 

你必須轉換array(這不是一個數組,順便)到號碼清單:

array = [int(n) for n in line.split()] 
+0

ahh很好,但仍然收到錯誤 – sbru 2013-05-02 06:58:51

+1

@bagelboy:在totalpoints + = points'附近可能是'TypeError'? – Blender 2013-05-02 06:59:20

+0

我更新了原始問題中的代碼和錯誤 – sbru 2013-05-02 07:00:54

0

您可能要封閉g.py加引號。

解釋器認爲g是一個你引用的變量,而不是你想要引用的文件名。

0

g.py必須由"g.py" 替代和totalpoints必須初始化