关于python:打印循环到文本文件

Printing Loop into a Text file

本问题已经有最佳答案,请猛点这里访问。

我想把它打印到一个文本文件中,但是我环顾四周,不知道该怎么做。

1
2
3
4
5
6
7
8
9
10
11
12
13
def countdown (n):
    while (n > 1):
        print('
'
,(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), '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), '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)


而不是。。。

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

使用…

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

甚至…

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

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

我希望这能给你点启发!


更为"正确"的是,它将被视为写入文本文件。您可以这样编码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def countdown (n):
    # Open a file in write mode
    file = open( 'file name', 'w')
    while (n > 1):
        file.write('
'
,(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), '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), '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)