0

I have a file like this:

a
D
c
a
T
c
a
R
c

I want to delete from specific line (in this case 3) until another specific line (in this case 5), so the file would look like:

a
D
c
a
R
c
4
  • 1
    What kind of file are you reading in? What do you want to do with the file after you read it in and remove these lines? More information is needed to better answer the question. Commented Jul 31, 2022 at 1:36
  • is a vcf file, i want to delete a specific contact, i've already did to separate any contact in a function, now i need to delete it if is repeated Commented Jul 31, 2022 at 1:38
  • You need to do the delete in place or in a seperate file ? Commented Jul 31, 2022 at 1:39
  • delete from the same file Commented Jul 31, 2022 at 1:39

1 Answer 1

1

I think this should work:

def delete_line_range(filename, start_line, end_line):
    # read all lines
    with open(filename, 'r') as f:
        lines = f.readlines()
    f.close()
    with open(filename, 'w') as f:
        # iterate trough lines
        for i in range(len(lines)):
            # check if line is out of range
            if i < start_line or i > end_line:
                f.write(lines[i])
    f.close()
    return

Or if you want to delete multiple ranges

def delete_line_ranges(filename, line_ranges):
    # read all lines
    with open(filename, 'r') as f:
        lines = f.readlines()
    f.close()
    with open(filename, 'w') as f:
        # iterate trough lines
        for i in range(len(lines)):
            # check if line is in range
            in_range = False
            for line_range in line_ranges:
                if i >= line_range[0] and i <= line_range[1]:
                    in_range = True
                    break
            # if not in range, write line
            if not in_range:
                f.write(lines[i])
    f.close()
    return

Where line_ranges is a list of tuples containing start and end line numbers.

Be aware that in both of these functions the line numbers start at 0. Means if you want to delete line 3 to 5 like in your example you need to subtract 1 from both start and end line number.

delete_line_range('test.txt', 2, 4) # deletes line 3 to 5 if you start counting from 1

Edit

Deleting Contacts out of vcf file.


Get range of specific contact:

def get_contact_range(filename, name):
    # read all lines
    with open(filename, 'r') as f:
        lines = f.readlines()
    f.close()
    for i in range(len(lines)):
        # check if line is start of contact
        if lines[i].startswith('BEGIN:VCARD'):
            start_line = i
            continue
        if name in lines[i]:
            for j in range(i, len(lines)):
                # check if line is end of contact
                if lines[j].startswith('END:VCARD'):
                    end_line = j
                    return (start_line, end_line)
    return None
print(get_contact_range('test.vcf', 'John Doe'))

test.vcf

BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//macOS 11.5.2//EN
N:Doe;John;;;
FN:John Doe
ORG:Sharpened Productions;
EMAIL;type=INTERNET;type=HOME;type=pref:[email protected]
EMAIL;type=INTERNET;type=WORK:[email protected]
TEL;type=CELL;type=VOICE;type=pref:123-456-7890
ADR;type=HOME;type=pref:;;12345 First Avenue;Hometown;NY;12345;United States
ADR;type=WORK:;;67890 Second Avenue;Businesstown;NY;67890;United States
NOTE:The man I met at the company networking event. He mentioned that he had some potential leads.
item1.URL;type=pref:https://fileinfo.com/
item1.X-ABLabel:_$!!$_
BDAY:2000-01-01
END:VCARD

Output:

(0, 15)

Combine the above functions:

def delete_contact(filename, name):
    # get start and end line of contact
    contact_range = get_contact_range(filename, name)
    # delete contact
    delete_line_range(filename, contact_range[0], contact_range[1])
    return

Multiple Contacts at once:

def delete_contacts(filename, names):
    # get start and end line of contacts
    line_ranges = []
    for name in names:
        contact_range = get_contact_range(filename, name)
        line_ranges.append((contact_range[0], contact_range[1]))
    # delete contacts
    delete_line_ranges(filename, line_ranges)
    return
Sign up to request clarification or add additional context in comments.

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.