将字符串传递给python中的open函数 [英] passing string to file open function in python

查看:237
本文介绍了将字符串传递给python中的open函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户输入,我想把它作为打开函数的文件名参数。这是我曾经试过的:
$ 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 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'

这篇关于将字符串传递给python中的open函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆