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() 的一些基本的用法:

 

 

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

 

 當然還可以動%來格式化就像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))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM