In order to write to a file you simply need to pass a string to file.write()
. In your case the same string you're printing.
One difference is that print
automatically adds a new line at the end of each string (because of the default value of the argument end='\n'
). So when writing to the file you can add an ending new-line. Alternatively, you can use print
's file
argument to avoid any change at all!
Now you just need to have the file descriptor available at the point where you want to write to it. That might depend on the design of the rest of your code, for simplicity of the example I will simply move it to the main
function.
One more thing is when read/write-ing files, it is better to use the with
context manager:
import random, sys
class KeyGen():
def __init__(self):
global i
i = int(input("How many serial codes are you looking for? \n"))
print("")
self.main(i)
def main(self, count):
""" Our main iteration function, using simple
capital letters, along with the numbers 0-9 """
seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
with open("demofile2.txt.", 'w') as text_file:
for i in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
# text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')
print("\nCreated {} serial keys.".format(count), file=text_file)
# text_file.write("\nCreated {} serial keys.\n".format(count))
if __name__ == '__main__':
app = KeyGen()
I will use this chance for a general tip:
In Python there is no need to over-use classes. Maybe you come from a Java background where everything is classes, but here your class only serves as a gate-way to a function. So your code could be:
import random, sys
def main():
"""
Our main iteration function, using simple
capital letters, along with the numbers 0-9
"""
seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
count = int(input("How many serial codes are you looking for? \n"))
with open("demofile2.txt.", 'w') as text_file:
for _ in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
# text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')
print("\nCreated {} serial keys.".format(count), file=text_file)
# text_file.write("\nCreated {} serial keys.\n".format(count))
if __name__ == '__main__':
main()