如何在 Python 中提示用户打开文件
我使用以下代码根据用户设置的路径打开文件,但出现错误。有什么建议吗?
f = raw_input("\n Hello, user. "
"\n \n Please type in the path to your file and press 'Enter': ")
file = open('f', 'r')
它说 f 未定义或不存在这样的东西......即使我正在定义它?使用“r”读取文件。
I'm using the following code to open a file based on the path set by the user, but am getting errors. Any suggestions?
f = raw_input("\n Hello, user. "
"\n \n Please type in the path to your file and press 'Enter': ")
file = open('f', 'r')
It says f is undefined or no such thing exists... even though I am defining it? Using 'r' to read the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不应将
f
放在引号中:'f'
表示由字母 f 组成的字符串,因此您的代码正在查找名为f
的文件代码>但没有找到它。相反,使用f
表示变量 f 的值。另外,不要调用变量来存储文件
file
。这很容易做到,但要尽量避免。已经有一个名为file
的内置类,最好不要用您自己的名称隐藏任何内置类或函数。这是因为您看到的其他代码将期望file
代表文件类而不是您的变量。查看术语是否正在使用的一种方法是使用
help
函数:由于缩进在 Python 中很重要,我建议在此处发布代码时确保缩进完全正确。
You shouldn't have the
f
in quotes:'f'
means the string consisting of the letter f so your code was looking for a file calledf
and not finding it. Instead usef
which means the value of the variable f.Also, don't call the variable to store your file
file
. This is easily done but try to avoid it. There is already a built-in class calledfile
and it's best practice not to hide any built-in classes or functions with your own names. This is because other code you see will expectfile
to represent the file class and not your variable.One way to see if a term is in use is to use the
help
function:And as indendation is significant in Python I'd recommend getting your indentation exactly right when posting code on here.
您正在尝试打开字符串“f”。试试这个:
You're trying to open the string 'f'. Try this:
不要将
f
放在引号中。f
是一个保存字符串的变量,但在 open 中您使用的是字符串值“f”。Don't put
f
in quotes.f
is a variable that is holding a string, but in your open you are using the string value 'f'.open() 返回一个文件对象,最常与两个参数一起使用:open(filename, mode)。
<代码>>> f = open('/tmp/workfile', 'w')
有关文件的更多信息,您可以查看此链接
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
>>> f = open('/tmp/workfile', 'w')
For more Information about Files U can Check out This Link