0

I am getting a weird error when I try to open a file in my python program even though they are in the same directory. Here is my code:

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()

and this is the error I am getting:

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

I am not quite sure why it is saying g is not defined, even though it is in the same directory as my python file.

1
  • You may want to fix the whitespace in your code. And it looks like you have some undefined variables as well? Commented May 2, 2013 at 7:02

3 Answers 3

5

g.py should be a string:

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

Also, array is a list of strings. Multiplying strings by integers just duplicates them:

>>> "1" * 4
"1111"

You have to convert array (which isn't an array, by the way) into a list of numbers:

array = [int(n) for n in line.split()]
Sign up to request clarification or add additional context in comments.

10 Comments

@bagelboy: Probably a TypeError near totalpoints += points?
@bagelboy: Your code and the error message don't match up. Are you editing the same file?
What do you mean by "don't match up"
@bagelboy: The error message points to a line of code that doesn't exist in your file: open(g.py, "r"). You already changed that.
yeah haha that is why I posted this on SO. It doesn't make sense to me. I save it and run it in the shell and it gives me that error
|
0

You might want to enclose g.py in quotes.

The interpreter thinks g is a variable you are referencing rather than a filename you intend it to reference.

Comments

0

g.py must be replaced by "g.py" and totalpoints must be initialized

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.