Remove Lines in Multiple .txt files (that start with 1 2 3 4 5) in Python

Question:

*** NOTE :::I have very little knowlege and programming background***

What i want :

I want to remove lines in txt files that start with 1 2 3 4 or 5 and keep only lines that start with 0

I have 9032 txt files in a folder and i want a python script to run in that folder and do all my line removal work…

here is sample of text file data image
enter image description here

i want output like this
enter image description here

the code i wrote … (ofcourse not working at all… wrong logics)

import os
import re
import glob


direc = r"C:UsershassaDesktopyolo_ssd_test"

os.chdir(direc)

yolo_files = os.listdir(direc)


file_count = 0

for file_name in yolo_files:

    file_count = file_count + 1
    # print(file_count,file_name)

for txt in glob.glob('*.txt'):
    with open(os.path.join(os.getcwd(), txt), 'r+') as input_append_file:
        text = input_append_file.read()
        for line in text:
            if not line.startswith("1"):  
               # line = line.replace('.' , '')
               input_append_file.write(line)

        for line in text:
            if not line.startswith("2"):  
               # line = line.replace('.' , '')
               input_append_file.write(line)

        for line in text:
            if not line.startswith("3"):  
               # line = line.replace('.' , '')
               input_append_file.write(line)

        for line in text:
            if not line.startswith("4"):  
               # line = line.replace('.' , '')
               input_append_file.write(line)

Some one please help me write a code for multiple files

Asked By: Hassan

||

Answers:

You’ve made this way more complicated than it should be.

for txt in glob.glob("*.txt"):
    lines = open(txt,'r').readlines()
    lines = [l for l in lines if l and l[0] == '0']
    open(txt,'w').writelines(lines)
Answered By: Tim Roberts
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.