使用Python删除多余的空白行

Raj*_*kar 1 python

我想在Python中使用Notepad ++的精彩功能"删除剩余空白行".

如果我有这样的文件,请说

A
B


C



D
Run Code Online (Sandbox Code Playgroud)

我想要

A
B

C

D
Run Code Online (Sandbox Code Playgroud)

这样做的pythonic方法是什么?

这是我试过的

A=['a','\n','\n','\n','a','b','\n','\n','C','\n','\n','\n','\n','\n','\n','D']
B=[]
count=0
for l in range(0,len(A)):
    if A[l]=='\n':
        count=count+1
    else:
        count=0
    if count>1:
        if A[l+1]=='\n':
            continue
        else:   
            B.append('\n')
    else:
        if A[l]!='\n':
            B.append(A[l])
print B
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 5

确保不会超过\n\n,例如:

import re
print re.sub('\n{3,}', '\n\n', your_string, flags=re.M)
Run Code Online (Sandbox Code Playgroud)

并且,itertools.groupby用于大文件:

from itertools import groupby

with open('your_file') as fin:
    for has_value, lines in groupby(fin, lambda L: bool(L.strip())):
        if not has_value:
            print
            continue
        for line in lines:
            print line,
Run Code Online (Sandbox Code Playgroud)