先看乙個簡單的例子:將變數寫入txt文字中
結果如圖:f = open('e:/test.txt','w')
f.write('hello world!')
out[3]: 12
f.close()
那麼如何將變數按行寫入呢?
在'w'寫入模式下,當我們下次寫入變數時,會覆蓋原本txt檔案的內容,這肯定不是我們想要的。txt有乙個追加模式'a',可以實現多次寫入:
結果如圖:f = open('e:/test.txt','a')
f.write('the second writing...')
out[6]: 21
f.close()
如果要按行寫入,我們只需要再字串開頭或結尾新增換行符'\n'即可:
結果如圖:f = open('e:/test.txt','a')
f.write('\nthe third writing...')
out[9]: 21
f.close()
如果想要將多個變數同時寫入一行中,可以使用writelines()函式:
結果如圖:f = open('e:/test.txt','a')
f.writelines(['\nthe fourth writing...',',','good'])
f.close()
參考:python教程:[56]寫入txt
python教程:[57]txt追加模式
python 按行讀取並判斷按行寫入檔案
f open description opinion.json w encoding utf 8 forline inopen test1set raw search.test1.json encoding utf 8 if question type description fact or opi...
按行方式寫入檔案 fputs函式
fputs 函式也是用來顯示字串的,它的原型是 函式原型 int fputs const char s,file stream s 代表要輸出的字串的首位址,可以是字元陣列名或字元指標變數名。stream 表示向何種流中輸出,可以是標準輸出流 stdout,也可以是檔案流。標準輸出流即螢幕輸出,pr...
Python按行讀檔案
1.最基本的讀檔案方法 file readline example 1.py file open sample.txt while 1 line file.readline if not line break pass do something 一行一行得從檔案讀資料,顯然比較慢 不過很省記憶體。在...