Remove empty lines in a text file
- tinyytopic.com
- 0
- on Feb 16, 2023
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:
- The function initializes an empty string called
output
to hold the updated content of the text file. - The
with
statement is used to open the text file specified intxtFile
and create a file object calledfile
. - The
for
loop iterates over each line in the file. - The
if
statement checks if the line is not a whitespace character, using theisspace()
method of the string. If the line is not empty, it is appended to theoutput
string. - 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’. - The updated content of the file, which is stored in the
output
string, is written to the file object using thewrite()
method. - 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.