在 Python 中将浮点值写入文件的正确格式是什么 [英] What is the correct format to write float value to file in Python

查看:44
本文介绍了在 Python 中将浮点值写入文件的正确格式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆浮点值,例如:

I have a bunch of float values, for example:

x1 = 1.11111111

x1 = 1.11111111

x2 = 2.22222222

x2 = 2.22222222

我想将这些值写入文件:

I want to write these values to a file:

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)

此时我在第二行出现错误:

At this point I got an error on the second line:

write() takes exactly one argument (2 given)

如何写入文件,以便在打开文件时看到以下格式:

How do I write to file such that when I open it, I see this format:

This is x1: 1,1111111
This is x2: 2,2222222

是的,文件必须是 ***.dat

And yes, the file has to be ***.dat

它不是 .txt

推荐答案

您写入文件的方式看起来就像是为写入函数提供了两个参数.所以你只需要传递一个参数.尝试将 x1 和 x2 转换为字符串,然后写入文件.

the way you are writing to the file looks like you are giving two arguments to write function. So you need to only pass one argument. try converting x1 and x2 into string and then write to the file.

f.write("This is x1 " + str(x1))
f.write("This is x2 " + str(x2))

这篇关于在 Python 中将浮点值写入文件的正确格式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆