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.
You shouldn’t have the
fin quotes:'f'means the string consisting of the letter f so your code was looking for a file calledfand not finding it. Instead usefwhich 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 calledfileand 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 expectfileto represent the file class and not your variable.One way to see if a term is in use is to use the
helpfunction:And as indendation is significant in Python I’d recommend getting your indentation exactly right when posting code on here.