Python从文件继续循环

2024-07-05 09:54:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,可以生成从000000000000ffffffffffff的字符,这些字符被写入文件。 我正在尝试实现一个检查,看看程序是否已关闭,这样我就可以从文件中读取,比如说在00000000781B,然后从文件中继续for循环。 中的变量“尝试”(对于to_attempt:)具有元组类型,并且始终从零开始

是否可以从指定的值继续for循环

import itertools

f = open("G:/empty/last.txt", "r")
lines = f.readlines()
rand_string = str(lines[0])
f.close()
letters = '0123456789ABCDEF'
print(rand_string)
for length in range(1, 20):
    to_attempt = itertools.product(letters, repeat=length)
    for attempt in to_attempt:
        gen_string = rand_string[length:] + ''.join(attempt)
        print(gen_string)

Tags: to代码inforstring字符lengthgen
1条回答
网友
1楼 · 发布于 2024-07-05 09:54:21

您必须将该值存储在文件中,以跟踪上次读取的值。我假设从000000000000运行到ffffffffffff的主for循环是to_attempt循环。您只需要将for循环的值存储在一个文件中。您可以使用新变量来跟踪它

try:
    with open('save.txt','r') as reader:
        save = int(reader.read())
except FileNotFoundError:
    save = 0
#rest of the code
    for i in range(save,len(to_attempt)):
        with open('save.txt','r') as writer:
            writer.write(i)
        #rest of the code
    

相关问题 更多 >