如何将每个项目数组添加到 python 中的特定行?

How to add each item array into specific line in python?

我有 file.txt:

textaaa 1
textbbb
textaaa 2
textbbb
textaaa 3
textbbb

我想通过先读取文件并尝试写入行来将数组 (cc) 中的值添加到特定行中:

cc = [10, 9, 8]

with open("file.txt", "r") as in_file:
    buf = in_file.readlines()
    
with open("file.txt", "w") as out_file:
    for line in buf:
        if line == "textbbb\n":
            for item in cc:
                line = line + "textccc %d\r" % (item)
        out_file.write(line)

然而,我得到的是:

textaaa 1
textbbb
textccc 10
textccc 9
textccc 8
textaaa 2
textbbb
textccc 10
textccc 9
textccc 8
textaaa 3
textbbb
textccc 10
textccc 9
textccc 8

我想要的是:

textaaa 1
textbbb
textccc 10
textaaa 2
textbbb
textccc 9
textaaa 3
textbbb
textccc 8

我认为问题出在最后一个 for 循环中。有解决这个问题的建议吗?

您需要对列表进行子集化而不是遍历它: 现在你正在这样做:

for line in buf:             #for each line of text
    if line == "textbbb\n":  # if there's a match...
        for item in cc:      # write a newline for each item in my list..
            [...]
    out_file.write(line)

因此,您的列表在每场比赛中都会被完全覆盖。写单个项目的一种非常快速和肮脏的方法是:

offset = 0
for line in buf:
    if line == "textbbb\n":
        line = line + "textccc %d\r" % (cc[offset])
        offset+=1
    out_file.write(line)

编辑:另外,请注意,如果您的文件的最后一行与您的“textbbb”模式匹配,此解决方案将不可避免地出错,因为这次将没有结束符('\n')。

您不需要每次查找 textbbb 时都遍历所有列表。在每次肯定检查后使用计数器并递增它就足够了:

cc = [10, 9, 8]

with open("file.txt", "r") as in_file:
    buf = in_file.readlines()

with open("file.txt", "w") as out_file:
    i = 0
    for line in buf:
        if line == "textbbb\n":
            line = line + "textccc %d\r" % (cc[i])
            i += 1
        out_file.write(line)

输出:

textaaa 1
textbbb
textccc 10
textaaa 2
textbbb
textccc 9
textaaa 3
textbbb

请注意,最后一行 (textccc 8) 未添加,因为最后一行是 textbbb,而不是 textbbb\n

您不想每次都遍历整个列表,而是每次只使用下一项。您可以使用计数器(请参阅其他答案)。此处显示的替代方法是使用 iter 创建一个迭代器,然后当您想要下一个值时,您在该迭代器上调用 next

cc = [10, 9, 8]

with open("file.txt", "r") as in_file:
    buf = in_file.readlines()

iterator = iter(cc)
with open("file.txt", "w") as out_file:     
    for line in buf:
        if line == "textbbb\n":
            item = next(iterator)
            line = line + f"textccc {item}\n"
        out_file.write(line)

如果您的 cc 列表的长度小于 "textbbb" 的出现次数,那么您将得到一种或另一种形式的异常。 (在这种情况下,它将是 StopIteration,但如果您使用计数器和列表索引,那么它将是 IndexError。)

另请注意使用 f-string 进行输出格式化。在您的代码中使用 % 进行字符串格式化现已弃用。