Home > Software design >  how to read multiple txt files and delete the lines that doesnt contain specific word and update the
how to read multiple txt files and delete the lines that doesnt contain specific word and update the

Time:10-03

I have many txt files with content like this :

707.0 126.0 714.0 130.0 706.0 145.0 700.0 141.0 small-vehicle 0
711.0 140.0 718.0 141.0 712.0 157.0 706.0 154.0 small-vehicle 1
917.0 124.0 920.0 117.0 938.0 124.0 933.0 131.0 small-vehicle 0
3540.0 1210.0 3550.0 1215.0 3543.0 1240.0 3534.0 1236.0 large-vehicle 0
3530.0 1204.0 3537.0 1206.0 3529.0 1236.0 3521.0 1230.0 large-vehicle 0
3582.0 1208.0 3594.0 1214.0 3581.0 1243.0 3570.0 1235.0 large-vehicle 0
2936.0 1082.0 2887.0 1197.0 2782.0 1152.0 2835.0 1044.0 plane 0
683.0 4294.0 734.0 4182.0 864.0 4227.0 820.0 4345.0 plane 0
798.0 4027.0 840.0 3915.0 976.0 3966.0 925.0 4082.0 plane 0
925.0 3806.0 1031.0 3742.0 1106.0 3869.0 1011.0 3929.0 plane 0
1620.0 3987.0 1640.0 4107.0 1539.0 4131.0 1509.0 4008.0 plane 0

and I want to save lines that contains "plane" in same file and update

CodePudding user response:

you can try to use .readlines()

ex:

# open file and read the data
# the data will be stored in a list, each line will be an element in the list
txt_file = open("file_name.txt")
data = txt_file.readlines()
txt_file.close()

string_contained_plane = []
for string in data:
    if "plane" in string:
        string_contained_plane.append(string)

when the code above is done, string_contained_plane should have all the lines you need and you can use .writelines(string_contained_plane) to write the data into any file opened.

CodePudding user response:

The python find() method may be useful for you.

But you should at least provide some code so that we can help you better.

https://www.w3schools.com/python/ref_string_find.asp

  • Related