简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM