网络编程
位置:首页>> 网络编程>> Python编程>> Python3将数据保存为txt文件的方法

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

作者:AI_盲  发布时间:2023-01-22 19:06:27 

标签:python,数据,保存,txt,文件

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")  # 换行

上面代码结果如下:

输入     

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

输出结果:

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


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文件的方法,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:https://blog.csdn.net/xwd18280820053/article/details/53008448

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com