如何将文本文件中指定的字符串附加到每行的末尾?

时间:2019-07-15 00:09:47

标签: python

文本文件为:

ar
abcd
ak
abcd
efgh
tx
abcd

我想以这样的结尾:

abcd, ar
abcd, ak
efgh, ak
abcd, tx

我有此代码:

    file_name1 = "file1.txt"
    file_name2 = "file2.txt"

    with open(file_name2, 'w') as out_file:
        with open(file_name1, 'r') as in_file:
            for line in in_file:
                if len(line) == 3:
                    out_file.write(line.rstrip('\n') + line + '\n')

但是,这会将同一行追加到长度为2(+ \ n)的任何行上。

2 个答案:

答案 0 :(得分:1)

将行放在一行上并保存最后看到的2个字母的行,并在每次遇到2个字母的行时对其进行更新。对于其他行,请在其最后加上保存的最后一行。

with open('source.txt') as source, open('dest.txt', 'w') as dest:
    last_two_lettered_line = None
    for line in source:
        line = line.strip()
        if not line:
            continue
        if len(line) == 2:
            last_two_lettered_line = line
            continue
        if not last_two_lettered_line:
            continue
        modified = '{line}, {two}'.format(line=line, two=last_two_lettered_line)
        dest.write(modified + '\n')

为您提供:

abcd, ar
abcd, ak
efgh, ak
abcd, tx

答案 1 :(得分:0)

文本文件中的主要问题是空行中的'\ n',然后遇到的下一个问题是,您只注意到长度为3的单词。

您可以使用此代码按单词编号来进行编码,如果要保持此格式,如果要执行相同的操作,但是要使单词长度小于单词,则可以更改它:

file_name1 = "file1.txt"
file_name2 = "file2.txt"

word_count = 0
with open(file_name2, 'w') as out_file:
    with open(file_name1, 'r') as in_file:
        for str in in_file:
            if (str != '\n'):
                word_count += 1
                if word_count % 2 == 1:
                    prev = str
                elif word_count % 2 == 0:
                    out_file.write(str.rstrip('\n') + ',' + prev)

您必须弄清术语是什么,以使其正确。 (因为该术语是仅在最后一个词之前附加第二个词,所以它起作用了)