在python中向文件打开函数传递字符串

2024-04-19 09:08:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户输入,我想把它作为open函数的文件名参数传递。这就是我所尝试的:

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

当用户输入是openMe.py时,出现错误

^{pr2}$

但是当用户输入"openMe.py“时,它工作得很好。我不明白为什么会这样,因为我认为filename变量是一个字符串。任何帮助都将不胜感激,谢谢。在


Tags: ofthe函数用户namepyinput文件名
2条回答

正如Ashwini所说,在python2.x中必须使用raw_input,因为input本质上是eval(raw_input())。在

input("openMe.py")最后似乎去掉了.py的原因是python试图找到一个名为openMe的对象并访问它的.py属性。在

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

在Python 2中使用raw_input

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

raw_input返回一个字符串,而input相当于eval(raw_input())。在

eval("openMe.py")是如何工作的:

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.

示例:

^{pr2}$

相关问题 更多 >