简体   繁体   English

Python嵌套循环未按预期工作

[英]Python nested loop not working as intended

I'm working on an assignment for school where I have a text file: data.txt which looks like this:(instead of 'name' there are actual names I just replaced them here) 我正在为一个学校作业,其中有一个文本文件:data.txt,它看起来像这样:(不是“名称”,而是实际的名称,我只是在这里替换了它们)

10001-31021 'name'    2015.12.30.   524432

10001-31121 'name'  2016.03.21. 765432

10012-34321 'name'  2016.02.20. 231231

10201-11021 'name'  2016.01.10. 2310456

And I have an update.txt which looks like this: 我有一个update.txt,看起来像这样:

2016.03.22.
10001-31021 'name'  +20000

10012-34321 'name'  +35432

10012-34321 'name'  -10000

10120-00123 'name'  +120334

10001-31021 'name'  +5000

10210-41011 'name'  -6000

10201-11021 'name'  +100210

12345-32100 'name'  +123456

And I have to make a newdata.txt file according to the changes to the last column that update.txt includes. 而且我必须根据对update.txt包括的最后一列所做的更改来制作一个newdata.txt文件。

This is my code so far: 到目前为止,这是我的代码:

adat = open("data.txt", "r")
newdata = open("newdata.txt", "w")
update = open("update", "r")

date = update.readline().decode("utf-8-sig").encode("utf-8").splitlines()
num_lines = sum(1 for line in open('update'))
elsociklus = 0
masodikciklus = 0

for num_lines in update:
    updateData = re.search("(.{11}\t)(\D+\t)([+-]\d+)", num_lines)
    elsociklus = elsociklus + 1
    print("elsociklus: " + str(elsociklus))
    for j in adat:
        data = re.search("(.{11}\t)(\D+\t)(\d{4}\.\d{2}\.\d{2}\.\t)(\d+)", j)
        masodikciklus = masodikciklus + 1
        print("masodikciklus: " + str(masodikciklus))
        if data != None:
            if updateData.group(1) == data.group(1):
                print("regi: " + data.group(0))
                print("update: " + updateData.group(0))
                print("uj: " + data.group(1) + data.group(2) + date[0] + "\t" + str(int(data.group(4)) + int(updateData.group(3))))
                newdata.write(data.group(1) + data.group(2) + date[0] + "\t" + str(int(data.group(4)) + int(updateData.group(3))))
                newdata.write("\n")
            else:
                print("nincs valtozas: " + data.group(0))

adat.close()
newdata.close()
update.close()

My problem is with the nested loop. 我的问题是嵌套循环。 I just can't figure it out why it isn't entering the inner loop for the second time. 我只是不知道为什么它没有第二次进入内循环。 It works perfectly on the first iteration but when entering the 2nd one in the outer loop it just ignores the inner loop. 它在第一次迭代中工作完美,但是在外部循环中输入第二个迭代时,它只是忽略了内部循环。

Thank you in advance for your help. 预先感谢您的帮助。

Thanks to codingCat for the answer. 感谢codingCat的回答。 I fixed the problem by returning my file pointer to the beginning of my file in the inner loop 我通过将文件指针返回到内部循环中文件的开头来解决了该问题

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

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