Sunday, 11 February 2018

python - Printing Loop into a Text file




I want to be able to print this in to a text file, however I have looked around and can't figure out what I need to do.



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)


Answer



Instead of...



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


Use...



myFile = open('123.txt', 'w')

...
print('123', '456', file = myFile)
...
myFile.close() # Remember this out!


Or even...



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


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


I hope this has led some light on you!


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...