简体   繁体   中英

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

*** 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在此处输入图像描述

i want output like this在此处输入图像描述

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

 import os import re import glob direc = r"C:\Users\hassa\Desktop\yolo_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

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)

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