我希望能够将其打印到文本文件中,但是我已经环顾四周,无法弄清楚我需要做什么。
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 :(得分: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!
我希望这能为你带来一些启示!
答案 1 :(得分: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)