1

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?

1
  • If you want your line number use for line_no, line in enumerate(myText) Commented May 10, 2013 at 13:08

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

print line.rstrip() is most likely right (who needs trailing space) - print line, is a possibility
2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.