Печать цикла в текстовый файл

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

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)

person Nataku62    schedule 08.11.2015    source источник
comment
Я осмотрелся, а что вы пробовали? SO - это не сервис для написания кода. Пожалуйста, поработайте над своей проблемой и вернитесь с кодом.   -  person Swastik Padhi    schedule 08.11.2015
comment
Было бы неплохо, если бы вы просмотрели веб-страницы, чтобы получить ответ на этот вопрос.   -  person repzero    schedule 08.11.2015


Ответы (2)


Вместо...

...
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!

Надеюсь, это пролило свет на вас!

person 3442    schedule 08.11.2015
comment
Действительно? Открываете файл в режиме чтения, но пытаетесь записать в него текст? - person Casimir Crystal; 08.11.2015
comment
@KevinGuan: Ой, извините. Пропустил;). - person 3442; 08.11.2015
comment
Это действительно решило проблему для меня, так что спасибо. - person Nataku62; 08.11.2015

Вернее, считалось бы записью в текстовый файл. Вы можете закодировать что-то вроде этого:

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)
person Craig    schedule 08.11.2015
comment
ick, давайте не будем затенять встроенные функции, такие как file. Обычно я вижу f, inf или outf, если нет лучшего описания, чем файл. - person Adam Smith; 08.11.2015
comment
@AdamSmith На самом деле в Python 3.x нет file встроенной функции. Но я согласен использовать f вместо file. - person Casimir Crystal; 08.11.2015
comment
Я не знал ни о каких встроенных командах .. Просто делал его более читабельным. Я согласен называть это f или как-нибудь еще. - person Craig; 08.11.2015
comment
@KevinGuan Я на самом деле не понимал, что они покончили с этим в Python3 (я так и не нашел для него хорошего применения). Спасибо за внимание - person Adam Smith; 08.11.2015
comment
@AdamSmith Да, здесь хороший вопрос SO :) - person Casimir Crystal; 08.11.2015