Welcome folks today in this blog post we will be removing
blank or empty lines from text file in command line using
python script. All the full source code of the application is shown below.
In order to get started you need to make an
app.py file and copy paste the following code
with open(file_path, "r") as file:
# read the file lines into a list
lines = file.readlines()
with open(file_path, "w") as file:
# write the non-blank lines back to the file
for line in lines:
stripped_line = line.strip()
file.write(stripped_line + "\n")
# specify the file path
file_path = "/path/to/file.txt"
# call the function to remove blank lines from the file
As you can see we are calling the
remove_blank_lines() method and inside it we are opening the
input text file and inside that we are using the
readlines() method to read all the lines and then we are removing the
lines which are blank or empty and then we are saving the
file . And here you need to replace the
path of the input text file.