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
CodePudding user response:
f = open("var", "r")
is wrong, var is a variable so you should use
f = open(var, "r")
CodePudding user response:
Generate two files to use in the demonstration.
filename_1 = 'test1.txt'
filename_2 = 'test2.txt'
with open(filename_1, 'w') as f_out:
test_text = '''
I am beginner to python and coding in general, and am attempting to pass a
\nvariable as an argument to the open() function.
'''
f_out.write(test_text)
with open(filename_2, 'w') as f_out:
test_text = '''
How to substitute a variable for a string when using the open() function in python
'''
f_out.write(test_text)
# Read using passed variable
with open(filename_1,'r') as f_in:
print(f_in.read())
with open(filename_2, 'r') as f_in:
print(f_in.read())