首页 > 编程 > Python > 正文

Python3将数据保存为txt文件的方法

2019-11-25 11:43:44
字体:
来源:转载
供稿:网友

Python3将数据保存为txt文件的方法,具体内容如下所示:

f = open("data/model_Weight.txt",'a')  #若文件不存在,系统自动创建。'a'表示可连续写入到文件,保留原内容,在原                      #内容之后写入。可修改该模式('w+','w','wb'等) f.write("hello,sha")  #将字符串写入文件中f.write("/n")         #换行  if __name__=='__main__':  fw = open("/exercise1/data/query_deal.txt", 'w')  #将要输出保存的文件地址  for line in open("/exercise1/data/query.txt"):  #读取的文件    fw.write("/"poiName/":/"" + line.rstrip("/n") + "/"")  # 将字符串写入文件中    # line.rstrip("/n")为去除行尾换行符    fw.write("/n")  # 换行

上面代码结果如下:

输入     

   

输出结果:

with open("data/model_Weight.txt", 'ab') as abc:  #写入numpy.ndarray数据  np.savetxt(abc, Data, delimiter=",")     #使用numpy.savetxt()写入数据,Data为要存的变量因为numpy.ndarray数                                    #据无法用write()写入,数据间用','相隔。f.write("/n") #换行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=',')  # 数组xnp.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(file, arr, allow_pickle=True, fix_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')读入数据

总结

以上所述是小编给大家介绍的Python3将数据保存为txt文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表