[英]How to marge current line with previous line in txt file based on some condition in python?
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.