[問題] 如何將.py檔的輸出內容寫出到.txt檔案?

看板Python作者 (海蒂)時間15年前 (2010/01/08 12:45), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
我欲讀入的方程式如下: def printMultiplierTable(): maxMultiplier = 10 n1 = 1 while n1 < maxMultiplier: n2 = 1 s = "" while n2 < maxMultiplier: n3 = n1*n2 if n3<= 9: s = s + " " + str(n1) + "*" + str(n2) + "=" + " " + str( n1*n2 ) n2 = n2 + 1 else: s = s + " " + str(n1) + "*" + str(n2) + "=" + str( n1*n2 ) n2 = n2 + 1 print s n1 = n1 + 1 if __name__=="__main__": printMultiplierTable() 其實這是一個寫出九九乘法表的小程式。 如果我要把程式中的九九乘法表寫到另一個txt檔 要如何做? fout = open('MultiplierTable.txt', 'wt') fin = open('??') --->這裡我不知道要放什麼 for line in fin: lines = line.strip() for line in lines: fout.write(line) ## 寫出資料 fout.write( "\n" ) ## 寫出換行字元 # 檔案有打開就要有關上, 以讓資料寫出去 fout.close() 謝謝各位指教:) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.217.78

01/08 14:39, , 1F
你的input應該沒有要從檔案讀取吧,所以該行去除掉就好了
01/08 14:39, 1F

01/08 15:19, , 2F
以標題來看,只要你輸出的內容是正確的,用個 > 就行了
01/08 15:19, 2F

01/08 15:20, , 3F
python your_python.py > your_textfile.txt
01/08 15:20, 3F
文章代碼(AID): #1BHhXJaH (Python)
文章代碼(AID): #1BHhXJaH (Python)