在 python 中使用 open() 函数时如何用变量替换字符串
How to substitute a variable for a string when using the open() function in python
我是 python 和一般编码的初学者,我正在尝试将变量作为参数传递给 open() 函数。
通常我会写这样的东西:
f = open("text.txt" , "r")
print(f.read())
但是我想按照这些思路做一些事情:
var = "text.txt"
f = open("var", "r")
print(f.read())
任何解释或资源都会非常有帮助,在此先感谢
f = open("var", "r")
是错误的,var是一个变量所以你应该使用
f = open(var, "r")
#################################################
# 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)
#############################################
# Demonstrate opening files using a 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())
我是 python 和一般编码的初学者,我正在尝试将变量作为参数传递给 open() 函数。
通常我会写这样的东西:
f = open("text.txt" , "r")
print(f.read())
但是我想按照这些思路做一些事情:
var = "text.txt"
f = open("var", "r")
print(f.read())
任何解释或资源都会非常有帮助,在此先感谢
f = open("var", "r")
是错误的,var是一个变量所以你应该使用
f = open(var, "r")
#################################################
# 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)
#############################################
# Demonstrate opening files using a 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())