1

So I'm attempting to clean up a text file that I have (it is actually a region file which can be loaded into the astronomy fits viewer DS9). I would like to remove/delete the entirety of any line/(s) which contain the keyword "red" in them, for an example:

image;circle(2384.21957861,231.579450647,10.3410929712) # color = red text = {24}

Would anyone know how this could be accomplished within python?

  • You shouldn't edit the file you are parsing, rather copy the desired lines to a new file. Regardless why couldn't you just iterate over the lines of the file and check `if 'red' in line`? – Jeremy Fisher Jun 03 '16 at 17:25
  • check this one http://stackoverflow.com/a/28057753 – algor Jun 03 '16 at 17:26
  • I haven't been able to find anything online which could guide me through this procedure or some similar. I'm very new to Python. –  Jun 03 '16 at 17:27

2 Answers2

2

Open an outfile (outfile.txt) for writing, and open your input file (textfile.txt), going line by line through the input file scanning for the keyword (red). If red is not in the line it writes it to the outfile.

with open('outfile.txt', 'w') as o:
    with open('textfile.txt') as f:
        for line in f.readlines():
            if 'red' not in line:
                o.write(line)

Make sure the files are within the same directory as the python script.

Copy and Paste
  • 496
  • 6
  • 16
0

Based on this answer suggested by @algor, you coul try:

f = open("textfile.txt","r+")
d = f.readlines()
f.seek(0)
for line in d:
    if 'red' not in line:
        f.write(i)
f.truncate()
f.close()
Community
  • 1
  • 1
ml-moron
  • 888
  • 1
  • 11
  • 22