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

标签 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 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 修改。 code> 循环,因此如果 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))

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

关于python - 如果文件中的行不为空,则将行连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919381/

相关文章:

python - 安装 PySpark

Python 日志记录 - 每个循环迭代的新日志文件

Python从末尾读取文件,文件很大,无法读入内存

java - 如何从 Eclipse 的动态 Web 项目路径中读取文件?

python-3.x - PyTorch 中的 softmax 变暗和变量 volatile

python-3.x - 如何在运行时应用程序中使用 opencv python 在图像上写入文本

在 Ubuntu 16.04 上安装 python GDAL 2.1

python - 无法将 Python 客户端连接到 Azure Cosmo Bd : Import pydocumentdb fails

java - 如何判断一个文件是图片、视频还是音频文件

python - 安全地评估简单的字符串方程