Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to same line of file in Python

I'm trying to write a program that generates keys to be used for registering accounts on a game I'm working on.
So far, I have everything working with prints but I'm stuck when trying to write to a file.

This is my current code:

import random
file = open('keys.txt', 'w')
chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
keys = 0
while keys <= 50:
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('')    
    keys += 1
file.close()

To get it to print to the file, I tried adding file.write(random.choice(chars), end='') underneath the print in the for loop, however I got a TypeError saying write() takes no keyword arguments.

To clarify, the code looked like this:

for i in range(0,4):
    print(random.choice(chars), end='')
    file.write(random.choice(chars), end='')
print('-', end='')

From searching around I think the problem is to do with the end='' in the file.write, but I'm not certain. Any ideas?

Thanks in advance.

like image 669
pythagon Avatar asked Apr 14 '26 08:04

pythagon


1 Answers

The print function writes its argument plus a line end to the file. Since in some cases you don’t want a line end, you can override this default parameter by explicitly saying print("string", end = '').

The write function writes only its argument. It does not know about line ends or other magic. Therefore you must not pass it such an extra argument.

If your program will live longer, you should structure it to look cleaner. The following code also fixes your “character” 10, which is really 2 characters.

import random
import string

def generateRandomKey():
  alphabet = string.ascii_uppercase + string.digits
  rnd = ''.join(random.choice(alphabet) for _ in range(16))
  return '%s-%s-%s-%s' % (rnd[0:4], rnd[4:8], rnd[8:12], rnd[12:16])

file = open('keys.txt', 'w')
for _ in range(50):
  file.write('%s\n' % generateRandomKey())
file.close()
like image 83
Roland Illig Avatar answered Apr 15 '26 20:04

Roland Illig