将字符串传递给python中的open函数 [英] passing string to file open function in python
问题描述
我有一个用户输入,我想把它作为打开函数的文件名参数。这是我曾经试过的:
$ b $ pre $ filename $输入文件名称输入文件名称$ b $如果用户输入是
> openMe.py 出现错误,
NameError:name'openMe'未定义
但是当用户输入openMe.py
时它工作正常。我很困惑,为什么这是这样的,因为我认为文件名变量是一个字符串。任何帮助将不胜感激,谢谢。
在Python中使用 raw_input
2:
filename = raw_input(输入等级文件的名称:)
原始输入返回一个字符串,而
输入
相当于eval(raw_input())
。
$ b $ <$>eval (openMe.py)
作品:
因为python认为在
openMe .py
,openMe
是一个对象,而
py
是它的属性,所以它首先搜索openMe
,如果没有找到
,则会引发错误。如果找到了openMe
,那么它会搜索
这个对象作为属性py
。
例子:
>>> eval(bar.x)#仅在栏停止
NameError:名称'bar'未定义
>>> eval(dict.x)#dict被找到,但不是`x`
AttributeError:类型对象'dict'没有属性'x'
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.解决方案Use
raw_input
in Python 2:filename = raw_input("Enter the name of the file of grades: ")
raw_input
returns a string whileinput
is equivalent toeval(raw_input())
.How does
eval("openMe.py")
works:Because python thinks that in
openMe.py
,openMe
is an object whilepy
is its attribute, so it searches foropenMe
first and if it is not found then error is raised. IfopenMe
was found then it searches this object for the attributepy
.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'
这篇关于将字符串传递给python中的open函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!