How to remove blank lines from a .txt file in Python
Hello programmers, in this tutorial, we will learn how to remove blank lines from a .txt file in Python.
We can remove blank lines from a .txt file by using the strip() function.
strip(): strip() function checks whether there is a leading and tailing blank or spaces, removes those spaces, and returns the character.
To show you this, we will first create a sample .txt file which going to consist of a lot of blank lines. Then we will find out how to remove the blank lines easily.
#Creating a .txt file with open('new_file.txt', 'w') as f: f.write('CodeSpeedy \n\n Technology \n\n\n Private \n\n\n Limited \n\n is \n\n an \n\n Information \n\n technology \n\n company') f = open("new_file.txt", "r") print(f.read())
CodeSpeedy Technology Private Limited is an Information technology company
- Then we open that file, and we create a new text file using “write” method to store characters that do not contain any blank lines.
- For this 1st we have to run a for loop which read lines from the text file and then we use the conditional statement “if” to check if there is a blank line or not using strip() function.
- strip() function removes those blank lines and stores those characters into a new text file with the help of the write() method.
- At last, we print our new text file which has no blank lines.
# opening and creating new .txt file with open("new_file.txt", 'r') as r, open('file.txt', 'w') as o: for line in r: #strip() function if line.strip(): o.write(line) f = open("file.txt", "r") print("New text file:\n",f.read())
New text file: CodeSpeedy Technology Private Limited is an Information technology company