如何将字母数字代码写入 Python 中的文件?

How to write alphanumeric codes to a file in Python?

我正在尝试创建随机数字并将它们存储在一个文件中,我进行了一些谷歌搜索并遇到了 pickle 函数。我完全按照教程的方式使用了它,现在我需要知道如何存储我在其中创建的所有代码?这是我的代码

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

在下一行 -

y = ''.join(x)

假设 x 是一个随机字符列表,例如 - `['a'、'x'、'c'、'j']

上面一行执行后,会得到y = 'axcj'

您可以使用 pickle 来序列化列表对象本身,因此您甚至不需要 yinUse 列表。

代码看起来像 -

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

请注意 ab 文件模式,它用于附加到文件,而不是覆盖它。

你的生成方式x过于复杂

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

现在,您可以简单地 print x 像这样的文件

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

如果您希望将 N 代码附加到文件

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)