在 for 循环中创建多个文本文档

Creating multiple text documents in a for loop

我正在尝试创建一个文本文件,其中包含以下格式的自定义生成的单词:3 个数字 + 2 个字母 + 3 个数字 示例:abc00dfeaaa98fff 等。

我可以使用单个文本文件实现我想要的,但是文件变得太大了,很难处理这么大的文件。如何更改我的代码以便将这些行保存在多个文本文件中?

from itertools import product
i = 1
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["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"]
f = open("D:\wordlist" + str(i) + ".txt", "w+")
for a in product(characters, repeat=3):
    for b in product(numbers,repeat=2):
        for c in product(characters, repeat=3):
            word = "".join(a + b + c)
            f.write(word+"\n")
            i += 1
            print(str(i)+"."+word)
            if i > 13824:
                f.close()
                f = open("D:\wordlist" + str(i//13824) + ".txt", "w+")
                continue



f.close()

你已经准备好了一切,只需要一个额外的变量(file_number)来控制你所在的文件。 最后你的代码应该看起来像

from itertools import product
i = 1
file_number = 0
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["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"]
f = open("D:\wordlist" + str(file_number) + ".txt", "w+")
for a in product(characters, repeat=3):
    for b in product(numbers,repeat=2):
        for c in product(characters, repeat=3):
            word = "".join(a + b + c)
            f.write(word+"\n")
            i += 1
            print(str(i)+"."+word)
            if i > 13824:
                f.close()
                file_number += 1
                f = open("D:\wordlist" + str(file_number) + ".txt", "w+")
                i = 1
                continue

f.close()