Skip to main content
 首页 » 编程设计

python之将字符串传递给python中的文件打开函数

2025年05月04日21bhlsheji

我有一个用户输入,我想将其作为打开函数的文件名参数传递。这是我尝试过的:

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

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

NameError: name 'openMe' is not defined 

但是当用户输入 "openMe.py"时它工作正常。我对为什么会这样感到困惑,因为我认为文件名变量是一个字符串。任何帮助将不胜感激,谢谢。

请您参考如下方法:

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

例子:

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