Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How To Remove Blank Lines From a .txt File In Node.js?
Next article icon

How to remove blank lines from a .txt file in Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • str.strip( )
  • str.isspace( )

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 using the str.strip() Method

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:

  • Open the input and output .txt files in read and write mode(r,w).
  • Using for loop to perform iteration.
  • Using str.strip() method to check if the line is empty after removing all the spaces from it.
  • The lines containing only spaces and empty string are filtered out.
  • Use the write() method to write the result of the file.

The following is an implementation of the above approach:

Python3
# opening and creating new .txt file with open(     "gfg.txt", 'r') as r, open(         'output.txt', 'w') as o:          for line in r:         #strip() function         if line.strip():             o.write(line)  f = open("output.txt", "r") print("New text file:\n",f.read()) 

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.

How to remove blank lines from a .txt file in Python using the str.isspace() Method

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:

  • Open the input and output .txt files in read and write mode(r,w).
  • Using for loop to perform iteration.
  • Using isspace() method to check if the line is empty. Non empty lines are added  to result.
  • Use the write() method to write the result of the file.

The following is an implementation of the above approach:

Python3
# opening and creating new .txt file with open(     "gfg.txt", 'r') as r, open(         'output.txt', 'w') as o:          for line in r:         #isspace() function         if not line.isspace():             o.write(line)  f = open("output.txt", "r") print("New text file:\n",f.read()) 

Output:

Hello Programmers    GFG is the best platform    This file is a sample for code in Python   Follow GFG website for more updates

Next Article
How To Remove Blank Lines From a .txt File In Node.js?

B

bytebarde55
Improve
Article Tags :
  • Technical Scripter
  • Technical Scripter 2022

Similar Reads

  • How To Remove Blank Lines From a .txt File In Node.js?
    Removing blank lines from a text file is a common task when working with data in text format. Blank lines can occur due to formatting errors, data entry mistakes, or during file generation. Node.js, with its non-blocking I/O and file system capabilities, makes it easy to automate this process. In th
    3 min read
  • How to remove brackets from text file in Python ?
    Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions.  Syntax: # import re module for using regular expression import re patn =  re.sub(pattern, repl, sent
    3 min read
  • How to delete from a pickle file in Python?
    Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dic
    3 min read
  • How to Find the Longest Line from a Text File in Python
    Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
    3 min read
  • How to search and replace text in a file in Python ?
    In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file b
    5 min read
  • Take input from user and store in .txt file in Python
    In this article, we will see how to take input from users and store it in a .txt file in Python. To do this we will use python open() function to open any file and store data in the file, we put all the code in Python try-except block. Let's see the implementation below. Stepwise Implementation  Ste
    2 min read
  • How to delete data from file in Python
    When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data. For more on file handling, check out: File Handling in P
    3 min read
  • How to read multiple text files from folder in Python?
    Prerequisite: File Handlingos Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python. Approach: Import modulesAdd path of the folderChange directoryGet the list of a file fr
    2 min read
  • Remove falsy values from a list in Python
    Removing falsy values from a list filters out unwanted values like None, False, 0 and empty strings, leaving only truthy values. It's useful for data cleaning and validation. Using List ComprehensionList comprehension is a fast and efficient way to remove falsy values from a list . It filters out va
    2 min read
  • How to read Dictionary from File in Python?
    A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences