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

标签 python file-io python-2.x

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

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'

关于python - 将字符串传递给python中的文件打开函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332921/

相关文章:

关于 PYTHONPATH 的 Python 2.x 多版本问题

Python:调用父实例方法

python - 一致地创建相同的随机 numpy 数组

python - 将多行字符串转换为数据框

python - 将索引的平面列表创建到数组中的正确正确的 numpy 方法

python - 将随机值分配给python程序中的参数

ios - IOS中文件夹的并行复制

java - Runnable .jar 和 Eclipse run 之间的行为非常不同

google-colaboratory - 如何在 google colab 上使用 Python 2?

java - 替代 Java 6 中的 Files#copy()