1

I have a user input and I want to pass it as the file name parameter of the open function. This is what I have tried:

filename = input("Enter the name of the file of grades: ")
file = open(filename, "r")

When the user input is openMe.py an error arises,

NameError: name 'openMe' is not defined

but when the user inputs "openMe.py" it works fine. I am confused as to why this is the case because I thought the filename variable is a string. Any help would be appreciated, thanks.

2 Answers 2

7

Use raw_input in Python 2:

filename = raw_input("Enter the name of the file of grades: ")

raw_input returns a string while input is equivalent to eval(raw_input()).

How does eval("openMe.py") works:

Because python thinks that in openMe.py, openMe is an object while py is its attribute, so it searches for openMe first and if it is not found then error is raised. If openMe was found then it searches this object for the attribute py.

Examples:

>>> eval("bar.x")  # stops at bar only
NameError: name 'bar' is not defined

>>> eval("dict.x")  # dict is found but not `x`
AttributeError: type object 'dict' has no attribute 'x'
Sign up to request clarification or add additional context in comments.

2 Comments

Why does eval("openMe.py") strip the .py?
@Sarien Because python thinks that in openMe.py, openMe is an object while py is it's attribute, so it searches for openMe first and if it is not found then error is raised.
1

As Ashwini said, you must use raw_input in python 2.x because input is taken as essentially eval(raw_input()).

The reason why input("openMe.py") appears to strip the .py at the end is because python attempts to find some object called openMe and access it's .py attribute.

>>> openMe = type('X',(object,),{})() #since you can't attach extra attributes to object instances.
>>> openMe.py = 42
>>> filename = input("Enter the name of the file of grades: ")
Enter the name of the file of grades: openMe.py
>>> filename
42
>>> 

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.