Python3將數(shù)據(jù)保存為txt文件的方法,具體內(nèi)容如下所示:
f = open("data/model_Weight.txt",'a') #若文件不存在,系統(tǒng)自動(dòng)創(chuàng)建。'a'表示可連續(xù)寫入到文件,保留原內(nèi)容,在原 #內(nèi)容之后寫入。可修改該模式('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") # 換行
上面代碼結(jié)果如下:
輸入?????
輸出結(jié)果:
with open("data/model_Weight.txt", 'ab') as abc: #寫入numpy.ndarray數(shù)據(jù) np.savetxt(abc, Data, delimiter=",") #使用numpy.savetxt()寫入數(shù)據(jù),Data為要存的變量因?yàn)閚umpy.ndarray數(shù) #據(jù)無(wú)法用write()寫入,數(shù)據(jù)間用','相隔。 f.write("\n") #換行 f.write("$***********world") #可對(duì)文件繼續(xù)寫入 f.close() #關(guān)閉
write可這樣寫入:f.write('%s%d%s%d%s%d%s'%("first",X,"_",Y,"_",Z,"hours ?:")) ?#X,Y,Z為整型變量,則寫入后內(nèi)容為firstX_Y_Zhours :(變量分別用值代替) ?
Example:?
x = y = z = np.arange(0.0,5.0,1.0) np.savetxt('test.out', x, delimiter=',') # 數(shù)組x np.savetxt('test.out', (x,y,z)) #x,y,z相同大小的一維數(shù)組 np.savetxt('test.out', x, fmt='%1.4e') #
參考網(wǎng)址:https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
numpy中保存其他文件格式的方法:
numpy.save(file, arr, allow_pickle=True, fix_imports=True) #保存為二進(jìn)制文件,格式:.npz
Example:
x = np.arange(10) np.save('finaname', x)
使用numpy.load(filename)讀入數(shù)據(jù)
[source]
numpy.savez(file,*args,**kwds)保存多個(gè)數(shù)組到文件,文件格式:.npz
Example:np.savez('data/first.npz', positiveSample=data1, negSample=data2)
同樣使用
numpy.load('data/first.npz')
讀入數(shù)據(jù)
總結(jié)
以上所述是小編給大家介紹的Python3將數(shù)據(jù)保存為txt文件的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
