简体   繁体   English

第一次迭代后Python脚本中断

[英]Python script breaks after first iteration

I am trying to do the following in python. 我正在尝试在python中执行以下操作。 Read xml file with usernames, pw, email addresses and so on. 使用用户名,密码,电子邮件地址等读取xml文件。 I then want to iterate through the passwords and try to find them in a different file. 然后,我想遍历密码并尝试在其他文件中找到它们。 if there is a match, print the username and password. 如果匹配,则打印用户名和密码。 this is what i have so far: 这是我到目前为止所拥有的:

import xml.etree.ElementTree as ET

tag = "multiRef"


tree = ET.parse('user.xml')
pwlist = open('swapped.txt', 'r')

for dataset in tree.iter(tag):
    password = dataset.find("password")
    pw = password.text
    user = dataset.find("username").text
    if pw in pwlist.read():
        print user
        print pw

Unfortunately, the script only prints one result and ends with no error or anything. 不幸的是,该脚本仅输出一个结果,并且没有错误或任何结尾。 I know, that there have to be at least 250 results... Why is it stopping after one result? 我知道,至少必须有250个结果...为什么在得到一个结果后停止? Absolute python newb, a detailed explanation would be much appreciated! 绝对是蟒蛇newb,详细的解释将不胜感激!

if pw in pwlist.read() shouldn't be inside the loop. if pw in pwlist.read()不应该在循环内。 The first time through the loop, read() will return the entire file. 第一次循环执行时,read()将返回整个文件。 The second time through it will return nothing because you are at END OF FILE. 第二次通过它不会返回任何内容,因为您位于文件尾。

Read the contents into a list prior to the loop and then refer to the list inside the loop. 将内容读入循环之前的列表中,然后在循环内引用该列表。

Also consider the pattern with open(...) as f to make sure you are closing the file, since I don't see an explicit close(). 还可以将with open(...) as f的模式with open(...) as f ,以确保您正在关闭文件,因为我没有看到显式的close()。

with open('swapped.txt', 'r') as f:
   pw_list = f.readlines()

for ...

The error is that you are calling read on each iteration. 错误是您在每次迭代中都调用read。 After one read you must call .seek(0) to reset the pointer. 读取一次后,必须调用.seek(0)重置指针。 That, however is a not the best solution for this, so you may want to try something like this: 但是,这并不是最佳解决方案,因此您可能需要尝试以下方法:

import xml.etree.ElementTree as ET

tag = "multiRef"


tree = ET.parse('user.xml')
with open('swapped.txt', 'r') as fin:
    pwlist = fin.read()

for dataset in tree.iter(tag):
    password = dataset.find("password")
    pw = password.text
    user = dataset.find("username").text
    if pw in pwlist:
        print user
        print pw

This way you only read the file once and close it afterward (by using a context manager ). 这样,您只读取一次文件,然后再关闭它(使用上下文管理器 )。 You can find more information on working with files in Python here . 您可以在此处找到有关在Python中处理文件的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM