0

Currently I'm writing just a simple program in python which allows for users to add and remove coordinates (as well as view them) from the game minecraft. Also allows you to enter a title.

Anyway, what I need help with is the remove feature. I want to search the text file for a specific string, so for example say "Oil Pool" is the string I want to search for. How would I do this?

After I search for the string I want to remove the next 6 lines (Including the string I searched for.)

Text File

This is a picture of what an entry in the text file looks like. So if I wanted to remove this entry, I'd want to search for "Huge Oil Pool" Then remove that, as well as the next 6 lines.

Thanks

Paul

2 Answers2

2

You may be better off using sed or awk for this specific task. However, if you insist on using python:

f = open('coordfile', 'r')
newcontents=""
linecounter=-1
for line in f:
    if linecounter>=0:
       linecounter+=1
    if "Oil Pool" in line: 
       linecounter+=1
    if linecounter>6:
       linecounter=-1
    if linecounter==-1:
       newcontents+=line
f.close()

f=open('coordfile', 'w')
f.write(newcontents)
f.close()
Kristóf Szalay
  • 1,177
  • 1
  • 8
  • 19
1

Perhaps something like this? This won't try to inhale the whole file into memory, and won't have a race window while the file is being rewritten. It does, however, require more disk space:

#!/usr/bin/python3

import os

with open('coordfile', 'r') as infile, open('coordfile.temp', 'w') as outfile:
    linecounter = -1
    for line in infile:
        if "Oil pool" in line:
            linecounter = 6
        if linecounter > -1:
            linecounter -= 1
            continue
        linecounter -= 1
        outfile.write(line)

os.rename('coordfile.temp', 'coordfile')
dstromberg
  • 6,954
  • 1
  • 26
  • 27