[英]Python nested loop not working as intended
我正在為一個學校作業,其中有一個文本文件: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
我有一個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
而且我必須根據對update.txt包括的最后一列所做的更改來制作一個newdata.txt文件。
到目前為止,這是我的代碼:
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()
我的問題是嵌套循環。 我只是不知道為什么它沒有第二次進入內循環。 它在第一次迭代中工作完美,但是在外部循環中輸入第二個迭代時,它只是忽略了內部循環。
預先感謝您的幫助。
感謝codingCat的回答。 我通過將文件指針返回到內部循環中文件的開頭來解決了該問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.