Home > Software engineering >  How to delete empty strings? [duplicate]
How to delete empty strings? [duplicate]

Time:10-04

How do I delete empty strings in some file.txt using python?

Some content

Some content
Some content
Some content

CodePudding user response:

How to delete all blank lines in the file with the help of python?

This question has an answer here.

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if line.rstrip():
        print line

CodePudding user response:

May be this will help you

Step 1 : Import python module os to run Unix command

Step 2 : For text processing sed command is best

Meaning :

  • d: delete
  • ^$: match the lines which are empty
  • i: in-place : This option specifies that files are to be edited in-place. GNU sed does this by creating a temporary file and sending output to this file rather than to the standard output

Code :

import os
os.system("sed -i \'/^$/d\' file.txt")

Their are many more methods but this is the simplest one using Unix within python

  • Related