如何有效地将数据保存到文件(我将在稍后绘制)?
我从我的研究中得到了这个:
#Open new data file
f = open("data2.txt", "w")
f.write( str(yEst) ) # str() converts to string
f.close()
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的一些代码:
for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
#print yEst
f.write( str(yEst) ) # str() converts to string
yEst=0
f.close()
Run Code Online (Sandbox Code Playgroud)
现在,当我打开我的文件" data2.txt"时,我无法读取数据,因为它没有"有条理".我怎样才能使用下一行,f.write( str(yEst) )以便我有一个包含我的'yEst'数据的列到文件"data2.txt?感谢您提前考虑:)
PS:yEst看起来像(在data2.txt文件中):48.901347147148.605785828748.114506165947.429486 ..我希望它作为一个列: - >
48.9013471471 (new line)
48.6057858287 (new line)
48.1145061659 (new line)
47.4294863684
etc ..
Run Code Online (Sandbox Code Playgroud)
Han*_*ele 11
你的意思是说你喜欢它自己的每一个数据点,就像这样吗?
48.9013471471
48.6057858287
48.1145061659
47.4294863684
Run Code Online (Sandbox Code Playgroud)
如果是这样,那么你可能想尝试这样的事情:
for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
f.write( str(yEst) + "\n" )
f.close()
Run Code Online (Sandbox Code Playgroud)
首先,要将每个数据点写入该行,它需要在循环内部 - 这就是为什么我在调用之前为该行添加了额外的空间f.write.
我添加的第二件事是+ "\n"- 这会将新行字符添加到行尾.您可以将其更改为您想要的任何内容!几个例子:
f.write( str(yEst) + " " ) 将在每个数据点后添加一个空格:
48.9013471471 48.6057858287 48.1145061659 47.4294863684
Run Code Online (Sandbox Code Playgroud)
f.write( str(yEst) + "|" ) 将在每个数据点后添加一个管道字符:
48.9013471471|48.6057858287|48.1145061659|47.4294863684|
Run Code Online (Sandbox Code Playgroud)
另一方面,如果您只是将数据保存为数组,请尝试以下操作:
yEst = 0 # or some initial value
yEstArray = []
for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392):
for x in range(1,N+1):
yEst = yEst + a * cos(x* i)
yEstArray.append(yEst)
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样迭代数组:
for yEst in yEstArray:
do something with yEst
Run Code Online (Sandbox Code Playgroud)
要么
for yEst, index in enumerate(yEstArray):
do something with yEst and its index
Run Code Online (Sandbox Code Playgroud)
Python有三种主要的内置方法来保存数据:
pickle 将对象序列化为文件;sqlite- 嵌入式SQL数据库,由许多ORM系统支持(添加该数据库是pickle对象存储的绝佳替代方案); 和json/ yaml- 用于Web的序列化,具有基本数据结构和类型.| 归档时间: |
|
| 查看次数: |
94653 次 |
| 最近记录: |