2015-11-08 28 views
-3

我希望能夠打印到一個文本文件,但是我環顧四周,無法弄清楚我需要做什麼。打印成一個文本文件循環

def countdown (n): 
    while (n > 1): 
     print('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottles of beer on the wall.') 
     n -= 1 
     if (n == 2): 
      print('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottle of beer on the wall.') 
     else: 
      print ('\n',(n), 'Bottle of beer on the wall,', (n), 'bottle of beer, take one down pass it around no more bottles of beer on the wall.') 

countdown (10) 
+0

**我看了看周圍**,你有什麼試過? SO不是代碼寫入服務。請處理你的問題,並回來一些代碼。 – CrakC

+0

這將是很好,如果你做一些網頁瀏覽來得到這個問題的答案 – repzero

回答

3

而不是...

... 
print('123', '456') 

使用...

myFile = open('123.txt', 'w') 
... 
print('123', '456', file = myFile) 
... 
myFile.close() # Remember this out! 

甚至......

with open('123.txt', 'w') as myFile: 
    print('123', '456', file = myFile) 

# With `with`, you don't have to close the file manually, yay! 

我希望這對導致一些光您!

+0

真的嗎?以**讀取模式打開文件**但嘗試向其中寫入文本? –

+0

@凱文關:哦,對不起。錯過了這一點;)。 – 3442

+0

這實際上解決了我的問題,所以謝謝。 – Nataku62

0

爲了更「正確」,它將被認爲寫入文本文件。你可以這樣編碼:

def countdown (n): 
    # Open a file in write mode 
    file = open('file name', 'w') 
    while (n > 1): 
     file.write('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottles of beer on the wall.') 
     n -= 1 
     if (n == 2): 
      file.write('\n',(n), 'Bottles of beer on the wall,', (n), 'bottles of beer, take one down pass it around', (n)-1, 'bottle of beer on the wall.') 
     else: 
      file.write('\n',(n), 'Bottle of beer on the wall,', (n), 'bottle of beer, take one down pass it around no more bottles of beer on the wall.') 

    # Make sure to close the file, or it might not be written correctly. 
    file.close() 


countdown (10) 
+2

我們不要像'file'那樣建造陰影。如果沒有比「文件」更好的描述,通常我會看到'f','inf'或'outf'。 –

+0

@AdamSmith實際上在Python 3.x中有** no **'file'內置函數。但我同意使用'f'而不是'file'。 –

+0

我不知道任何builtins ..只是讓它更可讀。我同意將它命名爲其他任何東西。 – Craig