with open()函数中,如何在文件名设置中引用变量(python)
name = "wangyang" age = "25" with open("C:/Users/mike1/Desktop/name_age.txt", "w", encoding = "utf-8") as f1: f1.write("hellow world")
这么写是不行的,文件名是name_age.txt,而不是wangyang_25.txt.
如下图:
正确的方式应该是用format()函数
name = "wangyang" age = "25" with open("C:/Users/mike1/Desktop/{0}_{1}.txt".format(name, age), "w", encoding = "utf-8") as f1: f1.write("hellow world")
如下图所示:
关于format() 的一些基本的用法:
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
Erick 2020-11-17
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16