passing string to file open function in python

若如初见. 提交于 2019-12-02 04:24:26

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'

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
>>> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!