-4

I am looking for a solution for a code. I need to delete a section of writing in a file using python, the chunk is 5 lines here's an example.

Numberplate: BN30CWS

Time In: Time In: 11:11:3

Time Out: Time In: 11:11:51

Speed: Your Speed: 48MPH

Was this vechile speeding?: No

(Without the gaps )

So if i enter BN30CWS i want those 5 lines to be deleted from the file (fileDocStandard) Please help, i have attempted making this working code for 4 hours now, and this is what i have come up with but it only deletes 1 line and wont delete the hole chunk

def deldata():
file = open(fileDocStandard, "r" )
array = []
for line in file:
    array.append(line)
file.close()

for i in range(len(array)):
    print (array[i])
let = input("Please enter the plate you want to delete ")
let = let.upper()
for i in range(len(array)):
    arrayitem = array[i]

    if (arrayitem[0]) == (let):
        del (array[i])
        break
file = open(fileDocStandard, "w")
file.close()
file = open(fileDocStandard, "a")
for i in range(len(array)):
    file.write(array[i])
file.close()   

Anyone see the issue, and can help me finally finish this?

Mike Marsh
  • 13
  • 4
  • 1
    I'm voting to close this question as off-topic because this isn't a code-writing or tutorial service – jonrsharpe Jun 30 '15 at 09:32
  • please mention your problem in detail, i couldn't get a word out of it! – Swastik Padhi Jun 30 '15 at 09:45
  • I have tried it yes, I have tried using arrays to read the file but i am un able to figure out how to delete it or sellect more than just 1 line – Mike Marsh Jun 30 '15 at 09:49
  • I am able to show someone my code so far, i just have tried for nearly 4 hours now and i cant figure this out – Mike Marsh Jun 30 '15 at 09:52
  • There's a lot of unnecessary steps in your code. Look at [Deleting a specific line in a file](http://stackoverflow.com/questions/4710067/deleting-a-specific-line-in-a-file-python), it should help. – Mel Jun 30 '15 at 12:14

1 Answers1

0

You can read your lines till you reach a line that BN30CWS is in it. then pass the next 5 line using itertools.islice and write your lines within a new file :

from itertools import islice

with open(fileDocStandard) as f,open(newfile) as out:
  for line in f:
       if 'BN30CWS' in f:
            f=islice(f,5,None)
       out.write(line)

And if you want to overwrite the file you can use tempfile:

with tempfile.NamedTemporaryFile(delete=False) as outfile:
    with open(fileDocStandard) as f:
      for line in outfile:
           if 'BN30CWS' in line:
                outfile=islice(outfile,5,None)
           out.write(line)
   os.rename(outfile.name, fileDocStandard)
Mazdak
  • 105,000
  • 18
  • 159
  • 188