我目前正在尝试创建一个简单的随机浮点数列表,将其保存在文本文件中,然后使用numpy.loadtxt加载带有numpy的浮点数列表。
出于某种原因,每当使用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'以下是代码示例:
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))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.
For some reason whenever using loadtxt it states that the file is empty.
/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))最满意答案
更改:
fp = open('mydata1.txt','w') for item in floats: str_item="{0:.5f}".format(item) fp.write("%s\n" % str_item ) fp.close成:
with open('mydata1.txt','w') as fp: for item in floats: fp.write("{0:.5f}\n".format(item))它应该工作。
with open()打开文件,并在您提交代码后立即将其关闭。 您的fp.close不会关闭该文件,因为您缺少括号。 它应该是: fp.close() 。 默认情况下,文件以缓冲模式打开。 因此,如果您不刷新或关闭文件,则不会将所有数据写入您的文件。
Change:
fp = open('mydata1.txt','w') for item in floats: str_item="{0:.5f}".format(item) fp.write("%s\n" % str_item ) fp.closeinto:
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. Your fp.close does not close the file because your are missing the parenthesis. It should be: 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.
更多推荐
发布评论