Python3將資料儲存為txt檔案的方法
阿新 • • 發佈:2020-01-09
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,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,z相同大小的一維陣列 np.savetxt('test.out',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檔案的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!