Python script to remove multiple blank lines between paragraphs and end of file -


i wrote python script capture data want have resulting text file contains multiple paragraphs each paragraph separated varying blank lines - anywhere 2 8.

my file has multiple blank lines @ end of file.

i python leave no more 2 blank lines between paragraphs , and no blank lines @ end of text file.

i have experimented loop , line.strip, replace etc have little idea how put together.

examples of have been using far

wf = open(file,"w+") line in wf:          newline = line.strip('^\r\n')          wf.write(newline)          wf.write('\n') 

it's easier remove blank lines , insert 2 blank lines between paragraphs (and none @ end) counting blank lines , removing if there's more two. unless you're dealing huge files don't think there's going performance difference between 2 approaches. here's quick , dirty solution using re:

import re # reads file f = open('test.txt', 'r+') txt = f.read() # removes blank lines txt = re.sub(r'\n\s*\n', '\n', txt) # adds 2 blanks between paragraphs txt = re.sub(r'\n', '\n\n\n', txt) # removes blank lines eof txt = re.sub(r'\n*\z', '', txt) # writes file , closes f.write(txt) f.close() 

before:

one line below  none below 3 below    eof 1 blank line below (stackoverflow's code thingy omits it) 

after:

one line below   none below   3 below   eof 1 blank line below 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -