kaoscify
kaoscify

Reputation: 1763

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? Using 'r' to read the file.

Upvotes: 0

Views: 23595

Answers (4)

David Webb
David Webb

Reputation: 193814

You shouldn't have the f in quotes:

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. Instead use f 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 called file 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 expect file 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:

>>> 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.

Upvotes: 6

ScoRpion
ScoRpion

Reputation: 11474

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

Upvotes: 0

AndrewR
AndrewR

Reputation: 6758

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'.

file = open(f, 'r')

Upvotes: 1

senak
senak

Reputation: 33

You're trying to open the string 'f'. Try this:

file = open(f, 'r')

Upvotes: 2

Related Questions