简体   繁体   English

如何提示用户在Python中打开文件

[英]How to prompt a user to open a file in Python

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? 它说f是未定义的,或者不存在这样的东西……即使我正在定义它? Using 'r' to read the file. 使用“ r”读取文件。

You shouldn't have the f in quotes: 您不应在引号中使用f

myfile = open(f, 'r')

'f' means the string consisting of the letter f so your code was looking for a file called f and not finding it. 'f'表示由字母f组成的字符串,因此您的代码正在查找名为f的文件,但未找到它。 Instead use f which means the value of the variable f. 相反,使用f表示变量f的值。

Also, don't call the variable to store your file file . 另外,请勿调用变量来存储文件file This is easily done but try to avoid it. 这很容易做到,但要避免这样做。 There is already a built-in class called file and it's best practice not to hide any built-in classes or functions with your own names. 已经有一个名为file的内置类,最佳做法是不要用自己的名称隐藏任何内置类或函数。 This is because other code you see will expect file to represent the file class and not your variable. 这是因为您看到的其他代码将期望file代表文件类而不是变量。

One way to see if a term is in use is to use the help function: 查看术语是否正在使用的一种方法是使用help功能:

>>> help(file)

Help on class file in module __builtin__:

class file(object)
 |  file(name[, mode[, buffering]]) -> file object
 |  
 |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
 |  writing or appending.  The file will be created if it doesn't exist

And as indendation is significant in Python I'd recommend getting your indentation exactly right when posting code on here. 而且由于indendation在Python中很重要,因此建议在此处发布代码时正确地使您的缩进正确。

You're trying to open the string 'f'. 您正在尝试打开字符串“ f”。 Try this: 尝试这个:

file = open(f, 'r')

Don't put f in quotes. 不要在引号中加上f f is a variable that is holding a string, but in your open you are using the string value 'f'. f是一个包含字符串的变量,但在打开时使用的是字符串值'f'。

file = open(f, 'r')

open() returns a file object, and is most commonly used with two arguments: open(filename, mode). open()返回一个文件对象,并且最常与两个参数一起使用:open(filename,mode)。

>>> f = open('/tmp/workfile', 'w')

For more Information about Files U can Check out This Link 有关文件的更多信息,您可以签出此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM