您的位置:首页 > 编程语言 > Python开发

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

2019-09-12 10:28 5008 查看

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文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 数据 保存 txt 文件
相关文章推荐