I have few .txt files I use to store configuration information for some python and shell scripts on my Pi. They are occasionally read from and very rarely written to. The Pi runs 24/7 mostly but will occasionally be unplugged from power so I can move it to a new location. I have noticed that sometimes the .txt files would suddenly become empty. Any idea what causes this? How it can be prevented?
It sounds like some files that are open/being read during shutdown may become corrupted and wiped. An easy solution is to include a button on the enclosure you are using that registers an interrupt and can issue a shutdown command to the RPi. This link describes how to implement an interrupt using one button and a few lines of python. I would also use the
os library and the classic
sudo reboot now or
sudo shutdown command.
As also suggested, adding a cron job that backs up the files periodically isn't a bad idea. An
@reboot ... line can also be added to your crontab to check if the file is empty and recover the last backup.