Python - 从.txt删除空行,但最后一行不要删除

时间:2018-04-17 13:43:09

标签: python file

我有一个像这样的test.txt文件:

1 - test
2 - 
3 - test
4 - 

(数字只是例如)

和我的python代码:

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line) 

但是output.txt是:

1 - teste
2 - teste
3 - 

我也想删除最后一行,但不要删除最后一行的代码:

lines = file.readlines()
lines = lines[:-1]

如果是空行,如何删除最后一行检查?

谢谢!

2 个答案:

答案 0 :(得分:0)

你在末尾有一个空行的原因是因为最后一行以换行结束。要从最后一行删除换行符,可以将所有行读入列表,然后删除最后一行:

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    # remove empty lines
    lines = [line for line in infile if line.strip()]

    # remove the newline from the last line
    if lines:
        lines[-1] = lines[-1].rstrip('\r\n')

    # write everything to disk
    outfile.writelines(lines)

答案 1 :(得分:0)

这是一个解决方案:

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    lines = "\n".join([line.strip() for line in infile if line.strip()])
    outfile.writelines(lines)