Stupid Beginner Question for Python Variables


#1

I’m trying out different ways to open and read files. So this way works fine:

print ("What file do you wish to open? “)
filename=input()
txt = open(filename)
print(f"Here’s your file {filename}:”)
print(txt.read())

That works fine, but then I thought I should be able to do this:

open(test.txt)
print(test.txt.read())

I don’t understand why the first way works but the second way doesn’t. I’m already in the same directory.
Or how about this?

filename=test.txt()
txt = open(filename)
print(txt.read())

How come neither of the last two pieces of code work, but the first one does?
Thanks in advance.


#2

You have to put quotes arround your filename, because Python reads the filename as a string:

# You need to assign your file to a variable in order to be
# able to do work with it.
file = open("test.txt")
print(file.read())

or

filename = "test.txt"
txt = open(filename)
print(txt.read())

The first one works because you ask the user with input() for the filename and every input from a user is a string.