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.