当我尝试在我的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 :(得分:5)
g.py
应为字符串:
file = open("g.py", "r")
此外,array
是一个字符串列表。用整数乘以字符串只是复制它们:
>>> "1" * 4
"1111"
您必须将array
(顺便说一下,不是数组)转换为数字列表:
array = [int(n) for n in line.split()]
答案 1 :(得分:0)
您可能希望将g.py括在引号中。
解释器认为g是您引用的变量,而不是您想要引用的文件名。
答案 2 :(得分:0)
g.py
必须由"g.py"
替换
并且必须初始化totalpoints