Replace multiple newlines with single newlines during reading file

前端 未结 3 1145
梦毁少年i
梦毁少年i 2021-02-14 11:55

I have the next code which reads from multiple files, parses obtained lines and prints the result:

import os
import re

files=[]
pars=[]

for i in os.listdir(\'pa         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 12:16

    You could use a second regex to replace multiple new lines with a single new line and use strip to get rid of the last new line.

    import os
    import re
    
    files=[]
    pars=[]
    
    for i in os.listdir('path_to_dir_with_files'):
        files.append(i)
    
    for f in files:
        with open('path_to_dir_with_files/'+str(f), 'r') as a:
            word = re.sub(r'someword=|\,.*|\#.*','', a.read())
            word = re.sub(r'\n+', '\n', word).strip()
            pars.append(word)
    
    for k in pars:
       print k
    

提交回复
热议问题