Python 利用格式化字符将多个字符串写入文件

Python 利用格式化字符将多个字符串写入文件

在网上搜索这个问题,例子都是现成的字符串写入,没有涉及到将多个字符创变量写入文件,初学Python,将自己摸索到的经验分享给大家。

// An highlighted block
filename = “test.txt”
target = open (filename, 'w')

print ("Truncating the file. Goodbay!")
# target.truncate()  #不明白截断的意义

print("Now I'm going to ask you for three lines.")

line1 = input("line 1:")
line2 = input("line 2: ")
line3 = input("line 3 :")

print("I'm going to write these to the file.")

target.writelines("%r\n%r\n%r\n"  %(line1, line2, line3)) #利用格式化字符

target.write(line1)#将输入的内容写入文件
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it.")
target.close()

版权声明:本文为qq_41889571原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。