Remove empty lines in a text file


How to remove empty lines from a text file?

The objective of this Python function is to read the contents of a file, remove any empty lines, and then overwrite the file with the updated content that no longer contains empty lines.

Ready-to-use Python function to remove empty lines from a text file:

def remove_empty_lines_text_file(txtFile):
    # Remove empty lines from the text file
    output = ''
    with open(txtFile) as file:
        for line in file:
            if not line.isspace():
                output+=line     
    file = open(txtFile, 'w+', encoding="utf-8")
    file.write(output)
    file.close()

Write your main code as a sample below,

remove_empty_lines_text_file("texts to remove empty lines.txt")

The output of the code is (check modified text file),

Before removing the empty lines:

import requests

# Define the API endpoint
url = "https://api.kite.trade/instruments" 

# Define headers

After removing the empty or blank lines:

import requests
# Define the API endpoint
url = "https://api.kite.trade/instruments" 
# Define headers
How does the function work?

The Python function remove_empty_lines_text_file takes one argument, txtFile, which is a string representing the path to a text file. The function’s goal is to read the contents of the file, remove any empty lines, and then overwrite the file with the updated content that no longer contains empty lines.

Here is a breakdown of how the function works:

  1. The function initializes an empty string called output to hold the updated content of the text file.
  2. The with statement is used to open the text file specified in txtFile and create a file object called file.
  3. The for loop iterates over each line in the file.
  4. The if statement checks if the line is not a whitespace character, using the isspace() method of the string. If the line is not empty, it is appended to the output string.
  5. After the loop has finished, the function reopens the file with write and read permissions using open() function with ‘w+’ argument. The encoding is specified as ‘utf-8’.
  6. The updated content of the file, which is stored in the output string, is written to the file object using the write() method.
  7. Finally, the function closes the file object with the close() method.

In summary, this function takes a text file, reads its content, removes any empty lines, and overwrites the file with the updated content that does not contain any empty lines.

Leave a Reply

Your email address will not be published. Required fields are marked *