Skip to content
Advertisement

How to substitute a variable for a string when using the open() function in python

I am beginner to python and coding in general, and am attempting to pass a variable as an argument to the open() function.

regularly I would write something like this:

f = open("text.txt" , "r")
print(f.read())

however I would like to do something along these lines:

var = "text.txt"
f = open("var", "r")
print(f.read())

Any explanations or resources would be very helpful, thanks in advance

Advertisement

Answer

f = open("var", "r") 

is wrong, var is a variable so you should use

f = open(var, "r")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement