2015-11-08 30 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