passing string to file open function in python

∥☆過路亽.° 提交于 2019-12-02 07:51:01

问题


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.


回答1:


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'



回答2:


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


来源:https://stackoverflow.com/questions/16332921/passing-string-to-file-open-function-in-python

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