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.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def remove_blank_lines(file_path): 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() if stripped_line: 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 remove_blank_lines(file_path) |
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.