简体   繁体   中英

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.

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()

end="" is a parameter of print function, not write .

But you can try this one:

file.write(str(random.choice(chars))+"\n")

Set it to the correct place then it will print them like print function.

Okay so as I wanted to generate 16 digit keys, I wrote the 4 character blocks to the file with dashes in between, and then I did file.write('\\n') at the end of the for loop block.

Thanks for your answers everyone, they were very helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM