[英]Loading floating numbers from txt file with python3 numpy
I am currently attempting to create a simple list of random floating numbers, save it in a text file and then loading the list of floating numbers with numpy
using numpy.loadtxt
. 我目前正在尝试创建一个简单的随机浮点数列表,将其保存在文本文件中,然后使用
numpy.loadtxt
使用numpy
加载浮点数列表。
For some reason whenever using loadtxt
it states that the file is empty. 由于某种原因,每当使用
loadtxt
它都会指出该文件为空。
/usr/local/lib/python3.4/dist-packages/numpy/lib/npyio.py:891: UserWarning: loadtxt: Empty input file: "mydata1.txt"
warnings.warn('loadtxt: Empty input file: "%s"' % fname)
[ ]
class 'numpy.ndarray'
Here is a sample of the code: 这是代码示例:
import numpy
import scipy
import matplotlib
from random import random
import codecs
floats = list(random() for i in range (10))
fp = open('mydata1.txt','w')
for item in floats:
str_item="{0:.5f}".format(item)
fp.write("%s\n" % str_item )
fp.close
floats2 = numpy.loadtxt("mydata1.txt",dtype="str", delimiter="\n")
for myfloat in floats2:
print("my floats is:",myfloat)
print(floats2)
print(type(floats2))
Change: 更改:
fp = open('mydata1.txt','w')
for item in floats:
str_item="{0:.5f}".format(item)
fp.write("%s\n" % str_item )
fp.close
into: 变成:
with open('mydata1.txt','w') as fp:
for item in floats:
fp.write("{0:.5f}\n".format(item))
and it should work. 它应该工作。
The with open()
opens the file and closes it as soon as you dedent your code. with open()
打开文件并在确定代码后立即将其关闭。 Your fp.close
does not close the file because your are missing the parenthesis. 您的
fp.close
不会关闭文件,因为您缺少括号。 It should be: fp.close()
. 应该是:
fp.close()
。 Per default, files are opened in buffered mode. 默认情况下,文件以缓冲模式打开。 So, if you don't flush or close the file no or not all data gets written to your file.
因此,如果不刷新或关闭文件,则不会或不是所有数据都写入文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.