Python 如果文件中的行不是emty,则将它们连接在一起

Python 如果文件中的行不是emty,则将它们连接在一起,python,file,python-3.x,newline,Python,File,Python 3.x,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 [NEWLINE] 所以我希望它看起来像这样 1:1 This is a simple sentence [NEWLINE] 1:2

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

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条线条上。如果后面的al行不是新行,则应合并为一行。 我想覆盖的给定文件以生成新文件

我尝试了一下while循环,但没有成功

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

但是这会创建一个无限循环。

您不应该在用例中嵌套
循环。代码中发生的情况是,
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))

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

您可以使用regex并删除single/n或/rHow您确定一个句子实际上位于多行吗?这对我来说不算什么。。。文件中必须有一个行尾字符,如\n或\r(或两者)。。。除非您使用的编辑器根据屏幕上编辑器的宽度“包装”。。。e、 g.如果您在windows上使用notepad.exe之类的工具,“格式”下拉菜单中有一个“Word Wrap”功能。如果选择该选项,它将根据窗口宽度包装句子。请更仔细地检查您的文件,以确保“包装的句子”不是由于您用来查看的工具造成的。嗯,Edwin.Oke,但是您建议如何创建一个新文件/覆盖另一个文件。所以我得到了当前需要的“语法”。append(I)确实给出了一个错误“AttributeError:'str'对象没有属性'append'”。对不起,这是我代码中的一个错误。我已经更新了答案。因为您应该使用
+
而不是
*
。您的表达式表示,删除前面有零个或多个数字,后面有零个或多个数字的所有“:”。这适用于任何“:”行中。好的,是的,我修好了,谢谢