在读取文件期间用单个换行符替换多个换行符 [英] Replace multiple newlines with single newlines during reading file

查看:82
本文介绍了在读取文件期间用单个换行符替换多个换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码,该代码从多个文件读取,解析获得的行并打印结果:

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('path_to_dir_with_files'):
    files.append(i)

for f in files:
    with open('path_to_dir_with_files'+str(f), 'r') as a:
       pars.append(re.sub('someword=|\,.*|\#.*','',a.read()))

for k in pars:
   print k

但是我在输出中有多个新行的问题:

But I have problem with multiple new lines in output:

test1


test2

相反,我想获得下一个结果,输出中不包含空行:

Instead of it I want to obtain the next result without empty lines in output:

 test1
 test2

以此类推.

我尝试过使用regexp:

I tried playing with regexp:

pars.append(re.sub('someword=|\,.*|\#.*|^\n$','',a.read()))

但是它不起作用.我也尝试使用strip()和rstrip()包括replace.这也行不通.

But it doesn't work. Also I tried using strip() and rstrip() including replace. It also doesn't work.

能请你帮忙吗?

推荐答案

您可以使用第二个正则表达式用一个新行替换多个新行,并使用strip摆脱最后一个新行.

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

这篇关于在读取文件期间用单个换行符替换多个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆