牛骨文教育服务平台(让学习变的简单)
博文笔记

Python3将数据保存为txt文件

创建时间:2016-11-02 投稿人: 浏览次数:17093

f = open("data/model_Weight.txt","a")    #若文件不存在,系统自动创建。"a"表示可连续写入到文件,保留原内容,在原

                                            #内容之后写入。可修改该模式("w+","w","wb"等)

f.write("hello,sha")   #将字符串写入文件中
f.write(" ")                 #换行    
with open("data/model_Weight.txt", "ab") as abc:    #写入numpy.ndarray数据
    np.savetxt(abc, Data, delimiter=",")          #使用numpy.savetxt()写入数据,Data为要存的变量因为numpy.ndarray数                                                                        #据无法用write()写入,数据间用","相隔。
f.write(" ")  #换行
f.write("$***********world")                #可对文件继续写入

f.close()                   #关闭

write可这样写入:f.write("%s%d%s%d%s%d%s"%("first",X,"_",Y,"_",Z,"hours  :"))  #X,Y,Z为整型变量,则写入后内容为firstX_Y_Zhours :(变量分别用值代替)  

Example:

x = y = z = np.arange(0.0,5.0,1.0)

np.savetxt("test.out", x, delimiter=",")   # 数组x
np.savetxt("test.out", (x,y,z))   #x,y,z相同大小的一维数组
np.savetxt("test.out", x, fmt="%1.4e")   # 
参考网址:https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
numpy中保存其他文件格式的方法:

numpy.save(filearrallow_pickle=Truefix_imports=True) #保存为二进制文件,格式:.npz

Example:

x = np.arange(10)
np.save("finaname", x)
使用numpy.load(filename)读入数据 [source] numpy.savez(file,*args,**kwds)保存多个数组到文件,文件格式:.npz Example:np.savez("data/first.npz", positiveSample=data1, negSample=data2) 同样使用numpy.load("data/first.npz")读入数据



                        -----------------<Python初学者小小经验>----------------

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。