Reputation: 19
Ok, so I have .txt files of each of these names below, I want the user to be able to pick a name, then that .txt is opened and printed. Does anyone know how I would do this? the main problem is the
f = open('name.txt','r')
where it is normal like this.
I thought it would be something like this
f = open(name'.txt','r')
but this gives me an invalid syntax.
I am quite new to all of this, it would be amazing if someone could help me out. This is Python btw :D
print("""here is the list of names.
John
Garry
Tom
Jim
Bob
Jerry
Timmy""")
name=input("please type the name you would like: ")
f = open('name.txt','r')
message = f.read()
print(message)
f.close()
Upvotes: 1
Views: 49
Reputation: 990
In order to open the correct file, you should do whats called a string concatenation:
print("""here is the list of names.
John
Garry
Tom
Jim
Bob
Jerry
Timmy""")
name = str(input("please type the name you would like: "))
f = open(name + '.txt','r')
message = f.read()
print(message)
f.close()
Can you paste the syntax error perhaps in case i am missing something else?
Upvotes: 0
Reputation: 51365
You just need to create your name file by concatenating name
and the string ".txt"
, which you can do with the +
operator:
name=input("please type the name you would like: ")
f = open(name + '.txt','r')
message = f.read()
print(message)
f.close()
Or, to make it more consise, the following is completely equivalent:
name=input("please type the name you would like: ")
with open(name + '.txt', 'r') as f:
print(f.read())
Upvotes: 3