Remove the last blank line from each text file

I have a lot of text files and each one has a blank line at the end. My scripts didn't seem to remove them. Can anyone please help?

# 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() 

      

+3


source to share


4 answers


you can remove the last blank line using:



with open(filepath, 'r') as f:
    data = f.read()
    with open(output, 'w') as w:
        w.write(data[:-1])

      

+2


source


You can try this without using the re module:

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

for filename in dir:
    if 'ABC' in filename: 
        filepath = os.path.join(filedir,filename)

        f = open(filepath).readlines()
        new_file = open(filepath, 'w')
        new_file.write('')
        for i in f[:-1]:

           new_file.write(i)

       new_file.close()

      



For each file path, the code opens the file, reads its contents line by line, then writes over the file, and finally writes the contents of file f to the file, except for the last element in f, which is an empty line.

+1


source


You can use Python rstrip()

to do it like this:

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 blank lines from the end of the file. It will not modify the file if there are no blank lines.

+1


source


I think this should work fine

new_file.write(f[:-1])

      

0


source







All Articles