Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last empty line from each text file

Tags:

python

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() 
like image 899
user8061394 Avatar asked May 24 '17 19:05

user8061394


People also ask

How do I delete all unnecessary consecutive blank lines?

Delete blank lines using the grep command When used with the -v option, the grep command helps to remove blank lines. Below is a sample text file, sample. txt, with alternative non-empty and empty lines. To remove or delete all the empty lines in the sample text file, use the grep command as shown.


2 Answers

You can use Python's rstrip() function to do this as follows:

filename = "test.txt"

with open(filename) as f_input:
    data = f_input.read().rstrip('\n')

with open(filename, 'w') as f_output:    
    f_output.write(data)

This will remove all empty lines from the end of the file. It will not change the file if there are no empty lines.

like image 193
Martin Evans Avatar answered Nov 15 '22 10:11

Martin Evans


you can remove last empty line by using:

with open(filepath, 'r') as f:
    data = f.read()
    with open(output, 'w') as w:
        w.write(data[:-1])
like image 45
Mohd Avatar answered Nov 15 '22 11:11

Mohd