如果文件中的行不为空,则将它们连接在一起

Concatenate lines together if they are not emty in a file

我有一个文件,其中一些句子分布在多行中。 例如:

1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over 
multiple lines and it goes on
and on.
[NEWLINE]
1:3 This is a line spread over
two lines
[NEWLINE]

所以我希望它看起来像这样

1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over multiple lines and it goes on and on.
[NEWLINE]
1:3 This is a line spread over two lines

有些行分布在 2 或 3 或 4 行中。如果后面有不是新行的所有行,则应将其合并为一行。 我想覆盖给定的文件以创建一个新文件。

我用 while 循环尝试过,但没有成功。

input = open(file, "r")
zin = ""
lines = input.readlines()
#Makes array with the lines
for i in lines:
    while i != "\n"
        zin += i
.....

但这会造成无限循环。

您不应在用例中嵌套 forwhile 循环。在您的代码中发生的事情是 for 循环将一行分配给变量 i,但它没有被嵌套的 while 循环修改,因此如果 while 子句是 True,那么它将保持这种状态并且没有中断条件,你最终会陷入无限循环。

解决方案可能如下所示:

single_lines = []
current = []

for i in lines:
    i = i.strip()
    if i:
        current.append(i)
    else:
        if not current:
            continue  # treat multiple blank lines as one
        single_lines.append(' '.join(current))
        current = []
else:
    if current:
        # collect the last line if the file doesn't end with a blank line
        single_lines.append(' '.join(current))

覆盖输入文件的好方法是将所有输出收集到内存中,读出后关闭文件并重新打开以写入,或者在读取输入时写入另一个文件并重命名第二个文件在关闭两者后覆盖第一个。