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.

如下图:

with open()函数中,如何在文件名设置中引用变量(python)

 

with open()函数中,如何在文件名设置中引用变量(python)

 

 

正确的方式应该是用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")

如下图所示:

with open()函数中,如何在文件名设置中引用变量(python)

 

 with open()函数中,如何在文件名设置中引用变量(python)

 

关于format() 的一些基本的用法:

with open()函数中,如何在文件名设置中引用变量(python)

 

 

number = 3.1415926
print("{0:f},{0:%},{0:e}".format(number))

with open()函数中,如何在文件名设置中引用变量(python)

 

 当然还可以动%来格式化就像C语言一样。

name = "wangyang"
age = 25
price = 99999.9999999
print("my name is %s"%(name))
print("my age is %d"%(age))
print("my price is %f"%(price))

with open()函数中,如何在文件名设置中引用变量(python)

相关文章:

  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
猜你喜欢
  • 2022-12-23
  • 2021-10-30
  • 2021-10-28
  • 2021-06-22
  • 2022-12-23
  • 2021-04-28
  • 2022-01-18
相关资源
相似解决方案