2012-09-06 15 views
0

是否可以將輸出到python shell的信息保存到txt文件中。將特定信息保存到python shell的txt

我運行Python版本2.7.2

這是什麼顯示在外殼。

Enter numbers 1... 22,34,35,40,55 
Enter numbers 2... 12,14,34,47,49 
Enter numbers 3... 1,4,10,19,30 
Section 1 
The number seqeuce is # 0 0 1 2 1 1 # <-- 
Section 2       
The number seqeuce is # 0 2 0 1 2 0 # <-- This is what I would like to save to txt. 
Section 3       
The number seqeuce is # 2 2 0 1 0 0 # <-- 

我環顧四周,並瞭解如何讀,寫和附加文件,但不 直接從殼。

我將不勝感激任何建議來解決這個問題。

回答

0

它在shell中是完全一樣的,但是你將基本上一次運行一行代碼,而不是僅僅運行一個文件。否則,你可以複製/粘貼結果... 不太確定,如果這就是你要找的,請告訴我,如果它不是。

+0

寫的代碼是問這個問題,shell給出了答案。如果可能,我想直接從shell中保存答案。 – Howie

+0

我認爲最簡單的方法就是複製/粘貼答案,誠實。否則,你可以嘗試挖掘[這裏](http://docs.python.org/library/stdtypes.html#bltin-file-objects)或[here](http://docs.python.org/tutorial/ inputoutput.html#讀取與寫入文件)。 –

+0

感謝您的反饋意見。 – Howie

0
>> numbers = input("Enter numbers") 
    >> with open('yourfile.txt', 'w') as f: 
     f.write('The number sequence is {0}'.format(numbers.replace(',', ' ')) 

如果輸入爲22,34,35,40,55,輸出文件將是The number sequence is 22 34 35 40 55

你只需要鍵入每個命令到外殼。當您運行.py腳本時,解釋器只是逐行評估您的代碼,就像shell在鍵入命令時所做的一樣。