How to write alphanumeric codes to a file in Python?

196 views Asked by At

I am trying to create random digits and have them stored in a file and I did some googling and came across the pickle function. I used it exactly how the tutorial did and now I need to know how to store all of the codes that I create in there? Here is my code

import string
import pickle
from random import randint

data = list(string.ascii_lowercase)
[data.append(n) for n in range(0, 10)]
x = [str(data[randint(0, len(data)-1)]) for n in range(0, 21)]
y = ''.join(x)

print (y)

inUse = []
inUse.append(y)

pickle.dump(inUse, open("data.pkl", "wb"))

inUse = pickle.load(open("data.pkl", "rb"))
2

There are 2 answers

3
John La Rooy On BEST ANSWER

Your way of generating x is overly convoluted

import string
import random
data = string.ascii_lowercase + string.digits
x = ''.join(random.choice(data) for n in range(20))

Now, you can simply print x to a file like this

with open("data.txt", "a")) as fout:
    print(x, file=fout)

If you wish to append N codes to the file

with open("data.txt", "a")) as fout:
    for i in range(N):
        x = ''.join(random.choice(data) for n in range(20))
        print(x, file=fout)
0
Anand S Kumar On

In the below line -

y = ''.join(x)

Lets say x is a list of random characters like - `['a', 'x', 'c', 'j']

After the above line executes, you will get y = 'axcj'

You can use pickle , to serialize the list object itself, so you would not even need y or inUse lists.

The code would look like -

import string
import pickle
from random import randint

data = list(string.ascii_lowercase)
[data.append(n) for n in range(0, 10)]
x = [str(data[randint(0, len(data)-1)]) for n in range(0, 21)]

pickle.dump(x, open("data.pkl", "ab"))

x = pickle.load(open("data.pkl", "rb"))

Please note the ab file mode, it is for appending to file, instead of overwriting it.