SD problems in Read/ f.truncate()
I'm working on a lopy4 + pysense i have a 8 Gb class 10 micro SD and i'm overall functionality that I want is:
When LoRa_Tx available transmit -> when not, save to SD -> when LoRa_Tx available again, read from SD, transmit information and delete line from log file.
I'm having problems with deleting the line from the log file, and the code that i have is the following
def delete_first_lines_from_file(filename, nr_lines): with open('/sd/' + LOG_FILENAME, 'r+') as f: # skip X lines for _ in range(nr_lines): if f.readline() == "": # reached End Of File before reading all lines print("#reached End Of File before reading all lines, truncating") f.seek(0) f.truncate() return eof = False #start saving to buffer and then write last_pos_read = f.tell() last_pos_write = 0 while eof is False: line_list =  f.seek(last_pos_read) # be ready for the next iteration and read the rest of the file for _ in range(nr_lines): line = f.readline() if line == "": eof = True break elif line == '\n': continue else: line_list.append(line) last_pos_read = f.tell() # go to begining, and start writing f.seek(last_pos_write) for line in line_list: f.write(line) last_pos_write = f.tell() f.truncate()
What i get is this:
Does truncate exists in micropython? Is there any equivalent way of doing this?
Thanks in advance!
@robert-hh do you see any solution to erase lines from the log file and keep them updated?
robert-hh last edited by robert-hh
@morrison trunctate does not exists. But if you open an existing file in just "w" mode, it is trunctated to 0. So instead of calling the first trunctate(),
- close the file
- reopen it in "w" mode.
- and optionally close it again (that is missing from your script)
For the second trunctate, I see no good solution.