Python中使用迭代器嵌套迭代两个文件时,最外层迭代只执行一次,里层正常如何解决?
写一个简单的密码测试工具,一个 user 文件,一个 pwd 文件,然后迭代 user 里面嵌套迭代 pwd ,结果 user 只迭代了一行, pwd 迭代正常,这是为啥?
就是 user 那个只迭代了一次就完事了,字典文件都是多行的。
求指点一下 是不是指针问题??
Python中使用迭代器嵌套迭代两个文件时,最外层迭代只执行一次,里层正常如何解决?
你的代码呢?
这个问题我遇到过,典型的迭代器耗尽问题。你用的应该是类似这样的代码:
with open('file1.txt') as f1, open('file2.txt') as f2:
for line1 in f1:
for line2 in f2:
print(f"{line1.strip()} - {line2.strip()}")
问题在于文件对象 f2 是一个迭代器,第一次外层循环时,内层循环会把 f2 迭代完,之后 f2 就空了。所以外层第二次循环时,内层循环直接跳过。
解决方案:
- 重置文件指针(推荐):每次外层循环时,把内层文件指针移回开头
with open('file1.txt') as f1, open('file2.txt') as f2:
for line1 in f1:
f2.seek(0) # 关键:重置文件指针
for line2 in f2:
print(f"{line1.strip()} - {line2.strip()}")
- 转换为列表:如果文件不大,直接读成列表
with open('file1.txt') as f1, open('file2.txt') as f2:
lines2 = list(f2) # 先缓存到列表
for line1 in f1:
for line2 in lines2:
print(f"{line1.strip()} - {line2.strip()}")
- 使用
itertools.product:更Pythonic的方式
from itertools import product
with open('file1.txt') as f1, open('file2.txt') as f2:
for line1, line2 in product(f1, f2):
print(f"{line1.strip()} - {line2.strip()}")
核心要点:记住迭代器只能遍历一次,用完了就得重置或重新创建。
总结:用 seek(0) 重置文件指针最直接。
因为执行完一次以后,里层的迭代器已经读完了
嗯嗯?图不显示么?我再粘一下文本版的 稍等
对 外层的只迭代一次 这是为何?
外层迭代了很多次,但是从第二次开始,里层已经是空的了,所以看起来什么都没做
python<br>def DictAttck(Host,UsernameFile,PasswordFile):<br> UserHandle = open(UsernameFile)<br> PwdHandle = open(PasswordFile)<br> for user in UserHandle:<br> for pwd in PwdHandle:<br> print Fore.RED + "[***] " + Style.RESET_ALL + "Try to UserName:%s Password:%s"%(user,pwd)<br> if chekpassword(Host,user,pwd) == 1:<br> print Fore.GREEN + "[OK] " + Style.RESET_ALL + "Got password. Username:%s Password:%s" %(user,pwd)<br> break<br>
break
哦哦 谢谢 那么怎么才能让里层从头开始呢?
谢谢 不是 break 的事情 注释掉过了
open 写到里面
感谢~懂了
PwdHandle.seek(0)

