当我尝试在我的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()
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
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
Run Code Online (Sandbox Code Playgroud)
我不太确定为什么它没有定义g,即使它与我的python文件在同一目录中.
g.py 应该是一个字符串:
file = open("g.py", "r")
Run Code Online (Sandbox Code Playgroud)
此外,array是一个字符串列表.用整数乘以字符串只是复制它们:
>>> "1" * 4
"1111"
Run Code Online (Sandbox Code Playgroud)
你必须转换array(顺便说一下,这不是一个数组)到一个数字列表:
array = [int(n) for n in line.split()]
Run Code Online (Sandbox Code Playgroud)