python - 在 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()
解决方案
你已经准备好了所有东西,只需要一个额外的变量(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()
推荐阅读
- node.js - Twitter API 在尝试发推文时给出此“消息:'对不起,该页面不存在',代码:34”“twitterReply:{错误:[[Object]]}”
- powershell - 当我关闭会话或注销计算机时,计划任务是在后台继续运行 Powershell 脚本的唯一方法吗?
- c++ - 在下面的示例代码中,我希望使用 _lseek(fh, 0L, SEEK_END) 获取文件中的字符数。但它返回零
- javascript - 使用 node-postgres 创建依赖于先前查询结果的查询
- python - 保存 Kakao 代币时出错
- matlab - 泊松过程:指数间到达时间 VS 指数服务持续时间
- r - 问题将第二个变量添加到 R 中的散点图
- assembly - 汇编函数地址表和函数下或数据段中的数据
- java - 如何使用 Apache Beam 和 Jackson 解析常规(不是换行符分隔的)json?
- java - 它们与第三类相关的两个类之间有什么关系?