0

I must concede I am fairly fresh to Python. What I want to do is to insert a new text line right before an ending line in a text file.

I managed to cobble a piece of code together that checks if a file exists, adds a header and an ending if it does not, checks conditions and if they are met, appends data to the file. The problem is, I am not able to figure out how to set the cursor on the penultimate line before appending, so that the file end line remains intact and data are correctly sandwiched in-between.

if os.path.exists('DaneGPIO.json') == False:
    with open ('DaneGPIO.json', 'a') as outfile:
        outfile.seek(0,0)
        outfile.write('{"status":[' + '\n')
        outfile.seek(0,2)
        outfile.write(']}')
        outfile.close
   with open ('DaneGPIO.json', 'rb') as filecount:
    count=sum(1 for line in filecount)
 while True:
    for number in sensor:
        precise = str(time.time())
        head, sep, tail = precise.partition('.')
        timestamp = time.strftime ("%Y-%m-%d %H:%M:%S")+"."+str(tail)
        time.sleep(0.5)
        previous_state = current_state
        current_state = GPIO.input(number)
        if current_state != previous_state:
            new_state = "HIGH" if current_state else "LOW"
            print("GPIO pin %s is %s" % (number, new_state))
            with open('DaneGPIO.json','a') as outfile:
                fieldnames = ("data","nrpinu","stan")
                json.dump ({'nrpinu':number,'data':timestamp, 'stan':     new_state}, outfile)
                outfile.write ('\n')    
                outfile.close

In short, I want to move to penultimate line before the json.dump takes place.

I followed Ashwini's suggestion from:

Printing to the penultimate line of a file

but his solution gives me the 'can't do nonzero end-relative seeks' message - apparently the method is not applicable in Python3. Many thanks in advance for your suggestions.

What I meant was how to set the pointer/cursor in-between the header and file ending, so I can do json.dump in that very spot. I already have the line count, I just wanted to point to a line "count-1" before performing json.dump.

Community
  • 1
  • 1
Tryglav
  • 1
  • 1
  • Question: how do you define "penultimate", regarding a possible trailing `\n`? – spectras Aug 11 '15 at 15:04
  • Far and away the easiest solution to problems like this is: 1. read the file into memory; 2. manipulate it in memory; and 3. write it back out over the old file. Once you have a list of lines, you're just an `insert` away from success. – jonrsharpe Aug 11 '15 at 15:07
  • @jonrsharpe That should be an answer, not a comment. With 50K+ rep., you don't really have a good excuse either. :/ – ereOn Aug 11 '15 at 15:11

0 Answers0