Creating a Test .txt File
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.
Python3
# message to be written to the .txt file msg = '''Hello Programmers \ \n\n\n\n\n GFG is the best \ platform \n\n\n\n\n This \ file is a sample for code \ in Python\n\n\n Follow GFG \ website for more updates''' # Creating a .txt file in Python with open ( 'gfg.txt' , 'w' ) as f: f.write(msg) |
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
How to remove blank lines from a .txt file in Python
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: