Skip to content Skip to sidebar Skip to footer

Input Data Not Defined

I am writing some code and need the user to input a file for use in the program: file=input('input file name') however, whenever you then input a file name (or anything for that m

Solution 1:

If you're using Python 2.x - you want to be using raw_input - input is used for something completely different in 2.x. If you're using Python 3.x - input is correct.

On a side note, the recommended style guide is to use open for opening files, so it's not too bad you're shadowing file here, but anyone expecting to be able to use file (basically the same as open) as a function might get a shock later.

Solution 2:

This is important:

input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).

Input will try to eval your input

Check this

In [38]: l =  input("enter filename: ")
enter filename: dummy_file
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Python27\<ipython-input-37-b74d50e2a058> in <module>()
----> 1 l =  input("enter filename: ")

C:\Python27\<string> in <module>()

NameError: name 'dummy_file' is not definedIn [39]: input /?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>String Form:<built-infunction input>
Namespace:  Python builtin
Docstring:
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

In [40]: file = raw_input("filename: ")
filename: dummy_file

In [41]: file
Out[41]: 'dummy_file'

using raw_input has it's disadvantages though.

Solution 3:

You need to use raw_input instead of input.

Input docsting :

input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

The python interpreter tries to eval your input, which will fail if it is a file name.

Solution 4:

input evaluates its argument, so when you give it something like my_text_file it will try to treat that as a variable. Use raw_input instead.

(Also, using file as a variable name is a bad idea, as it is also the name of a Python built-in class. Prefer something like path, filename, f.)

Post a Comment for "Input Data Not Defined"