![]() |
VOOZH | about |
Many times we face the problem where we need to remove blank lines or empty spaces in lines between our text to make it look more structured, concise, and organized. This article is going to cover two different methods to remove those blank lines from a .txt file using Python code.
This is going to be achieved using the following main methods:
First, we will create a file in .txt format where we will leave some missing or blank lines that can be removed later. The following code is used to create and save a file using Python only.
You would find the text file saved in your system with the same name. The following are the contents of the .txt file:
Hello Programmers GFG is the best platform This file is a sample for code in Python Follow GFG website for more updates
The str.strip() method in python removes all the spaces around the input string and returns the resulting string.
We are going to use the following approach to carry out our desired task:
The following is an implementation of the above approach:
Output:
Hello Programmers GFG is the best platform This file is a sample for code in Python Follow GFG website for more updates
In general, strip ( ) removes characters from both left and right based on the argument of the string (specifying the set of characters to be removed) but as we can see that no such argument has been provided thus strip ( ) will remove all the whitespaces in the text. That's why all the blank lines have been removed.
The str.isspace() method checks whether the specified character is whitespace or not and returns a boolean.
We are going to use the following approach to carry out our desired task:
The following is an implementation of the above approach:
Output:
Hello Programmers GFG is the best platform This file is a sample for code in Python Follow GFG website for more updates