2

I am trying to make a program that involves the user opening a file in python. Here is the relevant code:

def fileopen():
    source = input("Enter the name of the source file (w/ extension): ")
    f = open("%s" %source, "r") #open the file
    filelist = f.read()
    f.close()
    print(filelist)
    encrypt(filelist)

this is resulting in the following error:

Enter the name of the source file (w/ extension): source

Traceback (most recent call last):
  File "C:\Python27\Encrypt\Encrypt.py", line 27, in <module>
    fileopen()
  File "C:\Python27\Encrypt\Encrypt.py", line 2, in fileopen
    source = input("Enter the name of the source file (w/ extension): ")
  File "<string>", line 1, in <module>
NameError: name 'source' is not defined
>>> 

It was working when I was leaving it set as a static file (ex. source.txt) but I need to be able to select the file to use.

themightymanuel
  • 155
  • 2
  • 9

1 Answers1

4

Don't use input(); use raw_input() here:

source = raw_input("Enter the name of the source file (w/ extension): ")
f = open(source, "r")

input() evaluates the input as a Python expression. If you typed source at the prompt, Python tries to look that up as a variable name.

>>> input('Gimme: ')
Gimme: source
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'source' is not defined
>>> input('Gimme: ')
Gimme: Hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Hello' is not defined

raw_input() gives you just a string, nothing else.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343