简体   繁体   中英

Python Deleting Multiple Lines

I'm trying to delete certain repeating lines from a file I have. I am using the following code but it doesn't seem to work. There are no error messages just nothing has been deleted in the output file. I've attached the code below and a sample out what part of the file i'm trying to change looks like. Anyone able to help?

CODE:

infile = "angles"
outfile = "angles_1.txt"

delete_list = ["""ITEM: TIMESTEP
0
ITEM: NUMBER OF ENTRIES
18
ITEM: BOX BOUNDS pp pp pp
0 250
0 250
0 250
ITEM: ENTRIES c_11[1] c_11[2] c_11[3] c_11[4] c_22"""]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    for word in delete_list:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()

FILE I WANT TO CHANGE:

ITEM: TIMESTEP
0
ITEM: NUMBER OF ENTRIES
18
ITEM: BOX BOUNDS pp pp pp
0 250
0 250
0 250
ITEM: ENTRIES c_11[1] c_11[2] c_11[3] c_11[4] c_22 
1 2 3 1 180 
2 3 4 1 180 
3 4 5 1 180 
4 5 6 1 180 
5 6 7 1 180 
6 7 8 1 180 
7 8 9 1 180 
8 9 10 1 180 
9 10 11 1 180 
10 11 12 1 180 
12 13 14 1 180 
11 12 13 1 180 
15 16 17 1 180 
14 15 16 1 180 
13 14 15 1 180 
18 19 20 1 180 
17 18 19 1 180 
16 17 18 1 180 
ITEM: TIMESTEP
1000
ITEM: NUMBER OF ENTRIES
18
ITEM: BOX BOUNDS pp pp pp
0 250
0 250
0 250
ITEM: ENTRIES c_11[1] c_11[2] c_11[3] c_11[4] c_22 
2 3 4 1 154.251 

and it continues like this for a couple hundred repeats.

you have created a list with one element, but I suspect you want a list with many elements, one per line. Create it like so:

delete_list = """ITEM: TIMESTEP
0
ITEM: NUMBER OF ENTRIES
18
ITEM: BOX BOUNDS pp pp pp
0 250
0 250
0 250
ITEM: ENTRIES c_11[1] c_11[2] c_11[3] c_11[4] c_22""".split("\n")

Then in your for loop ( for line in fin ) just check if the entire line matches, if it doesn't then you write it to fout otherwise you skip it.

if line.strip() not in delete_list:
    fout.write(line)

Do this if your file is not that big. Read the whole file and replace the part as string.

infile = "angles"
outfile = "angles_1.txt"

delete_string = """ITEM: TIMESTEP
0
ITEM: NUMBER OF ENTRIES
18
ITEM: BOX BOUNDS pp pp pp
0 250
0 250
0 250
ITEM: ENTRIES c_11[1] c_11[2] c_11[3] c_11[4] c_22"""

fin = open(infile).read()
fin = fin.replace(delete_string, '')
fout = open(outfile, "w")
fout.write(fin)

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