【问题标题】:Why is for loop iterated only once?为什么for循环只迭代一次?
【发布时间】:2020-03-03 15:05:15
【问题描述】:

我对编码比较陌生,但由于我必须写几个字母,所以我想编写一个脚本来自动更改这封信中的名称。

我有一个包含名称占位符的文本文件和一个 csv 文件,其中名称以以下格式存储:

Surname;Firstname
Doe;John
Norris;Chuck
...

现在我想出了这个脚本:

import csv
import re

letterPATH = "Brief.txt"
tablePATH = "Liste.csv"


with open(letterPATH, "r") as letter, open(tablePATH, "r") as table:
    table = csv.reader(table, delimiter=";")
    rows = list(table)
    rows = rows[1::]
    print(rows)
    for (surname, firstname) in rows:
        #Check if first- and surname have correct output
        #print(firstname)
        #print(surname)

        for lines in letter:
            new_content = ""
            print(lines)
            lines = re.sub(r"\<Nachname\>", surname, lines)
            print(lines)
            lines = re.sub(r"\<Vorname\>", firstname, lines)
            print(lines)
            new_content += lines
        with open(surname + firstname +".txt", "w") as new_letter:
            new_letter.writelines(new_content)

我现在遇到以下问题: 有一个文件为每个条目创建了一个文本文件(JohnDoe.txt、ChuckNorris.txt 等),但是只有第一个文件具有正确的内容,而其他文件是空的。

在调试时,我发现第 18 行中的 for 循环只迭代了一次,而 with 语句按应有的方式迭代了多次。 我只是不明白为什么 for 循环不迭代。

干杯并感谢您的帮助! :)

【问题讨论】:

  • 在循环的第一次迭代中阅读了letter 中的所有行后,您位于该文件的末尾 - 进一步读取将不会返回任何内容,因为没有什么可进一步阅读的了。在循环开始之前,您每次都需要倒带文件(letter.seek(0)),或者将整个文件读入一个列表。

标签: python loops file for-loop


【解决方案1】:

letter 是一个文件。一个文件会记录您已阅读的内容以及下一次阅读的位置。因此,如果您已经阅读了两行,那么下一次阅读将在第三行,以此类推。

由于您第一次阅读了整个文件,因此下一次迭代将不再从文件中读取任何行,因为您已经阅读了它们。

解决方案可能是使用letter.seek(0) 方法将文件指针(指向您当前读取的文件中的位置)重置为开头。或者,您可以简单地将文件内容直接存储在列表中并遍历该列表。

import csv
import re

letterPATH = "Brief.txt"
tablePATH = "Liste.csv"


with open(letterPATH, "r") as letter_file, open(tablePATH, "r") as table:
    table = csv.reader(table, delimiter=";")
    letter = list(letter_file)  # Add all content to a list instead.
    rows = list(table)
    rows = rows[1::]
    print(rows)
    for (surname, firstname) in rows:
        #Check if first- and surname have correct output
        #print(firstname)
        #print(surname)

        for lines in letter:
            new_content = ""
            print(lines)
            lines = re.sub(r"\<Nachname\>", surname, lines)
            print(lines)
            lines = re.sub(r"\<Vorname\>", firstname, lines)
            print(lines)
            new_content += lines
        with open(surname + firstname +".txt", "w") as new_letter:
            new_letter.writelines(new_content)

【讨论】:

  • 非常感谢!我有一个类似的想法,但我不知道如何处理它:D
最近更新 更多