简体   繁体   English

python - 如何根据python中的某些条件将当前行与txt文件中的上一行合并?

[英]How to marge current line with previous line in txt file based on some condition in python?

My input text file is :我的输入文本文件是:

在此处输入图像描述

My expected output text file is :我预期的输出文本文件是: 在此处输入图像描述

Here we need to merge line 3 and 4 based on the condition that line 4 is not starting with "[" using python这里我们需要使用python根据第4行不是以“[”开头的条件合并第3行和第4行

Loop through lines, keep previous line in a variable.遍历行,将前一行保留在变量中。

If current line doesn't start with [ , add it to the previous line.如果当前行不以[开头,请将其添加到上一行。

Else save previous line to file and update it.否则将上一行保存到文件并更新它。

You can try something along the following lines:您可以尝试以下方式:

lines = []

with open("file_in.txt") as f_in:
    for line in f_in:
        if line.startswith("["):
            lines.append(line)
        else:
            lines[-1] += line  # append to last line

with open("file_out.txt", "w") as f_out:
     f_out.writelines(lines)

As mentioned above, \\n at the end of each line keeps the file same.如上所述,每行末尾的 \\n 保持文件相同。 "\\n" should be removed before merging lines.在合并行之前应删除“\\n”。 This should solve the problem.这应该可以解决问题。

lines = []

with open("file_in.txt") as f_in:
    for line in f_in:
        if line.startswith("["):
            lines.append(line)
        else:
            lines[-1] = lines[-1][:-1]
            lines[-1] += line  # append to last line

with open("file_out.txt", "w") as f_out:
     f_out.writelines(lines)

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

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