2013-05-02 130 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必须初始化