Repository navigation
Micropython file truncate doesn't exist #4775
Description
Activity
Hello,
Did-you find a solution for this problem. It does interest me because I have the same problem with a Lopy4I would use this if it was available
I finally defined my own truncate function:
def Truncate(self, Num):
with open("controle.txt","r") as FText: # controle.txt is the file to truncate
lignes = FText.readlines() # Read the content of the file
with open("controle.txt","w") as FText: # Create a new empty file controle.txt
for i in range(0,Num):
try:
FText.write(lignes[i]) # Paste one line by one line until Num
except:
passI'd appreciate having a
truncatefunction too. I'm trying to use the FAT file system for real-time data logging. I've noticed that it's best to write a bunch of blank data beforehand, because otherwise when you are logging your data, the file has to expand, and that can be slow (e.g. 70 ms on the RP2040). When I'm done with data logging, I'd like to truncate the file so it doesn't have blank data at the end.log = open("log", "w") blank_kb = "\n" * 1024 for i in range(16): log.write(blank_kb) log.seek(0, 0) print("\n", file=log) ... # log.truncate() would be nice here log.close()
Both the FatFS and LittleFS drivers provide a file truncate function, so this would be straight forward to implement (and of course make it match CPython).
Reacted by David Grayson- added a commit that references this issue
on Nov 11, 2024 I could also really use this for a mpy project that I'm working on
- addedenhancementFeature requests, new feature implementationsFeature requests, new feature implementations
on Oct 3, 2025 See #11500 for a PR that implements
truncate().
Is there any alternative in MicroPython to truncate a file at the current seek position? I don't want to just empty the file, I want to truncate it at a position.
The truncate function doesn't exist ( https://docs.micropython.org/en/latest/esp8266/tutorial/filesystem.html?highlight=open#creating-and-reading-files https://docs.micropython.org/en/latest/library/builtins.html?highlight=open#open )
Any alternatives?
I thought about copying the whole contents to a new file, but I wanted to avoid that since I'm limited to memory and storage(working on a LoPy4)