將python指令結果輸出到檔案

將python指令結果輸出到檔案

我想使用 python 作為計算器並將所有內容輸出到文件中。但

mamboleo@mamboleo-K56CB:~$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5**555 > output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'output' is not defined

它給了我一個錯誤,我找不到如何將結果輸出到文字檔案中。2>也不行。

答案1

 out = open("output.txt", "w")
 out.write(str(5*5+9))
 out.close()

你必須打開 python 文件物件才能做到這一點。如果運行 python 腳本,則可以使用“>”:

 python test.py > output

相關內容