我有一堆浮点值,例如:
x1 = 1.11111111
x2 = 2.22222222
我想将这些值写入文件:
f = open("a.dat", "w+")
f.write("This is x1: ",x1)
f.write("\n") #I want to separate the 2 lines
f.write("This is x2: ",x2)
此时我在第二行得到一个错误:
write() takes exactly one argument (2 given)
如何写入文件,以便在打开文件时看到以下格式:
This is x1: 1,1111111
This is x2: 2,2222222
是的,文件必须是 ***.dat
这不是.txt
请您参考如下方法:
write 函数采用单个字符串。您正在尝试像 print 那样使用它,它接受任意数量的参数。
事实上,您可以只使用 print 。默认情况下,它的输出只会转到程序的输出 ( stdout ),通过向它传递一个 file 参数,您可以将它发送到一个文本文件:
print("This is x1: ", x1, file=f)
如果您想使用write,您需要将输出格式化为单个字符串。最简单的方法是使用 f 字符串:
f.write(f"This is x1: {x1}\n")
请注意,我必须在末尾包含一个 \n。 print 函数将其 end 参数添加到它打印的内容的末尾,默认为 \n。 write 方法没有。
既是为了向后兼容,也是因为有时它们更方便,Python 有其他方法可以做同样的事情,包括显式 string formatting :
f.write("This is x1: {}\n".format(x1))
... printf-style formatting :
f.write("This is x1: %s\n" % (x1,))
... template strings :
f.write(string.Template("This is $x1\n").substitute(x1=x1))
…和字符串连接:
f.write("This is x1: " + str(x1) + "\n")
除了最后一个以外,所有这些都会自动将 x1 转换为字符串,其方式与 str(x1) 相同,但也允许其他选项,例如:
f.write(f"This is {x1:.8f}\n")
这会将 x1 转换为 float,然后以 8 位精度对其进行格式化。因此,除了打印出带有 8 位小数的 1.11111111 和 2.22222222 之外,它还会将 1.1 打印为 1.10000000和 1.23456789012345 作为 1.23456789。
相同的格式字符串适用于 f 字符串、str.format 和 format 函数:
print("This is x1: ", format(x1, '.8f'), file=f)
f.write("This is x1: {:.8f}\n".format(x1))
f.write("This is x1: " + format(x1, '.8f') + "\n")
…和其他两种方法有相似但不那么强大的格式化语言:
f.write("This is x1: %.8f\n" % (x1,))
