with open () function, how to reference variables (python) in the file name settings

name = "wangyang"
age = "25"

with open("C:/Users/mike1/Desktop/name_age.txt", "w", encoding = "utf-8") as f1:
    f1.write("hellow world")


    

So write does not work, the file name is name_age.txt, rather than wangyang_25.txt.

As shown below:

 

 

 

It should be the right way is to use format () function

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")

As shown below:

 

 

 

Some basic usage of format () is:

Guess you like

Origin www.cnblogs.com/zijidefengge/p/12089305.html