1

I use Linux, I tried to rename all my image files in a folder using this code :

import os

i = 0
path = os.chdir("/home/saran/Documents/twitter content")
for file in os.listdir(path):
    if file == "rename.py" :
     continue   
    new_file = "tweet{}.png ".format(i)
    os.rename(file, new_file)
    i = i + 1

It worked and all files were renamed like this : tweet1.png tweet2.png tweet3.png tweet4.png,etc

but when I accidentally ran the code a second time, half of the image files were deleted... Is there any way to recover them? Looks like the files which have the same name were replaced cause I ran the code twice, I need to restore them, Is it possible to do it? Thanks!

1 Answers1

1

File deletion and renaming is unfortunately irreversible as far as the os is concerned. Probably the only option would be to use some kind of data carving tool to search for png file headers and sizes if the images happen to be of similar sizes.

I think this happens to everyone at some point so maybe a few tips on how to prevent this in the future:

  1. always make a copy of the target directory before you run any scripts that either remove or rename files. This usually only takes seconds and prevents this kind of disasters.
  2. make regular backups of your system. E.g. I use borg with a dedicated HDD kept offline. Again it's super easy to setup, takes little to no time and disk space is cheap.
  3. use the str's zfill method when naming files with numbers (to get e.g. tweet001.png instead of tweet1.png). os doesn't attempt to parse integers from filenames hence os.listdir returns tweet1.png, tweet10.png, ..., tweet2.png instead of tweet1.png, tweet2.png, ..., tweet10.png
Michal Racko
  • 462
  • 2
  • 4
  • thanks, can't believe my 3 hours of hard work went waste because of that stupid mistake... I'll be careful next time, thank you sir – Saran Pariyar Sep 02 '22 at 04:52