user2361273
user2361273

Reputation: 57

How to delete a line from a file using python

I am using following code to find all the lines which contains ':' special character. Later I am trying to remove those lines from the file -

myFile = open('myPOST.txt', 'rb')
    myText = myFile.readlines()
    for line in myText:
             line.find(":") == "-1"
         if line.find(":"):

Is there any function in python that returns exactly the line where this character is found (find() returns either -1 or location of the searched character in the line) Or if I use find() only then how to delete exactly those lines for which the value of find() is -1?

Upvotes: 1

Views: 364

Answers (2)

cmd
cmd

Reputation: 5830

If you just want to do it within your existing program without having it be a command line utility like fileinput excels.

with open("myPOST.txt", "rb") as my_file:
    for line in my_file:
        if ":" not in line:
            # do whatever you want here
            # these are only the lines that do not have a ':' character

if you just want to find the line numbers

with open("myPOST.txt", "rb") as my_file:
    line_numbers = [lnum for lnum, line in enumerate(my_file) if ":" in line]

Upvotes: 2

jamylak
jamylak

Reputation: 133764

Using fileinput

Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place.

myPOST.txt

abc
de:f
ghi

import fileinput
for line in fileinput.input('myPOST.txt', inplace=True): 
    if ':' in line:
        continue # skip it
    print line.rstrip('\n') # stdout redirected to file

myPOST.txt

abc
ghi

The good thing about this solution is that it doesn't use .readlines() which loads the whole file into memory, instead it writes to a temporary file which is renamed to the original.

Upvotes: 4

Related Questions