2015-11-08 6 views
-3

Я хочу, чтобы иметь возможность напечатать это в текстовый файл, однако я посмотрел вокруг и не могу понять, что мне нужно сделать.Loop печати в текстовый файл

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

@KevinGuan: О, извините. Пропустил это;). – 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

ick let's not shadow builtins как 'file'. Обычно я вижу 'f',' inf' или 'outf', если нет лучшего описания, чем« файл ». –

+0

@AdamSmith На самом деле в Python 3.x есть встроенная функция ** no ** 'file'. Но я соглашаюсь использовать 'f' вместо' file'. –

+0

Я не знал о каких-либо встроенных устройствах .. Просто сделал его более читаемым. Я согласен с тем, чтобы назвать его f или что-то еще. – Craig