欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2022-03-13 12:55:22|栏目:Python代码|点击:

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=',')  # 数组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(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')读入数据

总结

上一篇:python实现自幂数的示例代码

栏    目:Python代码

下一篇:Python将xml和xsl转换为html的方法

本文标题:Python3将数据保存为txt文件的方法

本文地址:http://www.codeinn.net/misctech/196038.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有