Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Script to Remove Blank or Empty Lines From Text File in Command Line

Posted on February 12, 2023

 

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

 

 

Python
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.

 

Recent Posts

  • Node.js OfficeGen Example to Add Text & Images in Powerpoint Presentation in Javascript
  • Node.js OfficeGen Example to Generate Excel Files By Adding Data inside Cells & Sheets in Javascript
  • Node.js OfficeGen Example to Create Word Docx Files & Add Text Images inside it Using Javascript
  • React.js Twitter API Tutorial to Embed Profile & Timeline, Hashtags of User in Browser Using Javascript
  • Android Java Tutorial to Change Styles & Visibility of System Bars (Top, Action & Status) Full Example
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme