首页 > 解决方案 > 在 for 循环中创建多个文本文档

问题描述

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

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

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

标签: pythonfor-loopiterationitertoolscartesian-product

解决方案


你已经准备好了所有东西,只需要一个额外的变量(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()

推荐阅读