我是 python 和一般編碼的初學者,并試圖將變數作為引數傳遞給 open() 函式。
我經常會寫這樣的東西:
f = open("text.txt" , "r")
print(f.read())
但是我想按照以下方式做一些事情:
var = "text.txt"
f = open("var", "r")
print(f.read())
任何解釋或資源都會非常有幫助,在此先感謝
uj5u.com熱心網友回復:
f = open("var", "r")
是錯誤的, var 是一個變數,所以你應該使用
f = open(var, "r")
uj5u.com熱心網友回復:
生成兩個檔案以在演示中使用。
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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/435094.html
