简体   繁体   中英

How to write alphanumeric codes to a file in Python?

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

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.

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)

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