Python: 读写文件时换行

Python: line termination while reading and writing files

我编写了一个简单的实用程序,可以从文件中删除某些行。它将文件读入行列表 (Python),并将它们作为单个连接字符串写回,保留新行;一些行被删除,一些在这个过程中得到评论;变化的百分比可以忽略不计。 diff 以某种方式向我展示了一个大红色方块 before 和一个大绿色方块 after。肉眼看来,生成的文件看起来相当不错;我想过与尾部空间或类似的东西有一些细微的差别,但这真的可能吗?如果我在每一行中添加一些不可见的东西,那么每条红线后面都会有相应的绿线。大概是这样吧。

更新:

好吧,有人告诉我,行尾是肯定的。我的代码要点:

def check_file(path):
    out_line = ""
    with open(path, "r") as f_r:
        for line in f_r.readlines():
            drop_it, o_line = consume_line(line)
            if drop_it:
                pass
            else:
                out_line += o_line
    with open(path, "w") as f_w:
        f_w.write(out_line)

consume_line() 本质上是 returns 它的论点。在某些不常见的情况下,它可能会被安排删除或 uncommented/commented 退出 C++ 样式。在任何情况下都不会手动摆弄行尾。

如果没有删除任何行,则没有编辑报告总行数有任何变化。文件在 Linux.

上生成和处理

此代码设置文件中第一个 eol 之后的所有行结尾。保留尾随空格。

g_newline = ''


def current_nl(f):
    global g_newline

    if g_newline:
        return g_newline
    g_newline = f.newlines
    if isinstance(g_newline, tuple):
        print('!!! Something wrong. This is supposed to be the first eol in the file\n')
        return '\n'
    return g_newline


def check_file(path):
    global g_newline

    g_newline = ''
    out_line = ""

    with open(path, "r") as f_r:
        for line in f_r.readlines():
            drop_it, o_line = consume_line(line)
            if drop_it:
                pass
            else:
                out_line += o_line.rstrip('\n') + current_nl(f_r)
    with open(path, "w") as f_w:
        f_w.write(out_line)