Skip to main content
 首页 » 编程设计

python之使用 Python 删除多余的空行

2025年05月04日12birdshome

我想在 Python 中使用 Notepad++ 的精彩功能“删除多余的空行”。

假设我有这样的文件

A 
B 
 
 
C 
 
 
 
D 

我要

A 
B 
 
C 
 
D 

执行此操作的 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 

请您参考如下方法:

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

import re 
print re.sub('\n{3,}', '\n\n', your_string, flags=re.M) 

并且,对大文件使用 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,