[Solved] How to delete lines in a file based on the indices in a list


Create a set with the numbers that you need to delete and keep updating it while you read new lines. If the new line starts by one element in the set skip it and do not write it to the output file.

to_delete = set()

with open('input_file', 'r') as input_file, open('output_file', 'w') as output_file:
    for line in input_file:
        first, _, raw_list, *_ = line.split('\t')
        if int(first) in to_delete:
            continue
        output_file.write(line)
        to_delete.update(ast.literal_eval(raw_list))

2

solved How to delete lines in a file based on the indices in a list