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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-02 我要评论

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')读入数据

总结

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

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们