在python中,如何将内容写入一个文件,其中一部分包含变量,另一部分仅包含一个display语句?
如何在Python中使用在python中,如何将内容写入一个文件,其中一部分包含变量,另一部分仅包含一个display语句?,python,python-2.7,Python,Python 2.7,如何在Python中使用write()来编写类似“a is的值:”,a 我们使用 print "value of a is:",a 但是 给出了一个错误。如何将其写入文件???我想这就是您想要的: with open('somefile.txt', 'w') as the_file: the_file.write("value of a is: {}\n".format(a)) 我想这就是你想要的: with open('somefile.txt', 'w') as the_file
write()
来编写类似“a is的值:”,a
我们使用
print "value of a is:",a
但是
给出了一个错误。如何将其写入文件???我想这就是您想要的:
with open('somefile.txt', 'w') as the_file:
the_file.write("value of a is: {}\n".format(a))
我想这就是你想要的:
with open('somefile.txt', 'w') as the_file:
the_file.write("value of a is: {}\n".format(a))
接受完整的字符串,而不是以下格式之一:
"value of a is:",a
不要调用f.write(“a is的值:,a)
,而是首先将a is的值:,a分配给变量:
string = "value of a is:", a
f.write(string)
接受完整的字符串,而不是以下格式之一:
"value of a is:",a
不要调用f.write(“a is的值:,a)
,而是首先将a is的值:,a分配给变量:
string = "value of a is:", a
f.write(string)
如果a是整数:
f.write("value of a is: %d" % (a))
如果您正在寻找更健壮的解决方案,请参阅:如果a是整数:
f.write("value of a is: %d" % (a))
如果您正在寻找更健壮的解决方案,请参阅:我想您正在寻找以下代码:
a=10
f=open("test.dat","w")
f.write('valiue is a is:'+str(a))
f.close()
因为f.write()需要一个字符缓冲区对象,所以您必须将in转换为字符串才能写入您的文件我想您需要查看以下代码:
a=10
f=open("test.dat","w")
f.write('valiue is a is:'+str(a))
f.close()
因为f.write()需要一个字符缓冲区对象,所以您必须将in转换为字符串才能写入文件到目前为止您尝试了什么?问题没有说明他尝试了什么吗?@charvi try:
print>>f,“a的值为:”,a
这不起作用..到目前为止你尝试了什么?问题没有说明他尝试了什么吗?@charvi try:print>>f,“a的值是:”,a
这不起作用。。