holaprofesor
holaprofesor

Reputation: 271

Opening a file with a name error

I am trying to build a function that asks the user to input the name of a file, opens the file, reads its contents, prints the contents of the file on the screen, and closes the file. If no such file exists, it's okay if the script crashes. When I run the function, it gives me: NameError: name 'myInput' is not defined, and I'm not sure how to fix it.

Here is what I have so far:

print(input('Please enter the name of a file that you want to open.' + myInput)) with open(r"C:\Python32\getty.txt", 'r') as infile: data = infile.read() print(data)

Help if you can..

Upvotes: 1

Views: 5009

Answers (3)

kirkbyo
kirkbyo

Reputation: 61

I think something like this would solve your problem

fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 882821

myInput is an undefined variable, and I can't fathom what you had in mind by using it.

Maybe where you show the code...:

print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:

you actually meant something very different, e.g like...:

myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:

...?

Upvotes: 4

Newb
Newb

Reputation: 2930

In your first line, you have:

print(input('Please enter the name of a file that you want to open.' + myInput))

do you have myInput defined? You need to define it. If you don't have it defined before that line, your script will crash.

This can be gleaned from your helpful error message:

NameError: name 'myInput' is not defined

Which means that the variable myInput is not defined, so the compiler doesn't know what to put there.

Upvotes: 2

Related Questions