Remove the last empty line from each text file

Viewed 8918

I have many text files, and each of them has a empty line at the end. My scripts did not seem to remove them. Can anyone help please?

# python 2.7
import os
import sys
import re

filedir = 'F:/WF/'
dir = os.listdir(filedir)

for filename in dir:
    if 'ABC' in filename: 
        filepath = os.path.join(filedir,filename)
        all_file = open(filepath,'r')
        lines = all_file.readlines()
        output = 'F:/WF/new/' + filename

        # Read in each row and parse out components
        for line in lines:
            # Weed out blank lines
            line = filter(lambda x: not x.isspace(), lines)

            # Write to the new directory 
            f = open(output,'w')
            f.writelines(line)
            f.close() 
5 Answers

You can remove the last blank line by the following command. This worked for me:

file = open(file_path_src,'r')
lines = file.read()
with open(file_path_dst,'w') as f:
    for indx, line in enumerate(lines):    
       f.write(line)
       if indx != len(lines) - 1:
          f.write('\n')
Related