So Python is getting useful to me for avoiding manual repetitive tasks. I used it to rename a lot of folders. There were around 700 folders in 28 zip files which I needed to rename and re-zip. That would have been really cumbersome if not for Python.
The folders’ name were like 0001 – abc 1 . Only that the numbers didn’t match. The first number was used for arrangement and it was the second number according to which I had to change the first number. Doing that for 700 folders would have been a real pain. Luckily I knew Python and wrote a script for doing this.
Here’s the Python script that I used.
import zipfile import os import shutil CUR_DIR = os.getcwd() FILES_IN_CUR_DIR = os.listdir(CUR_DIR) def get_new_name(original_name): num = 0 started= False for c in original_name[7:]: if not c.isdigit(): if started is True: break continue else: started = True num *= 10 num += int(c) return str(num).zfill(4) + original_name[4:] def extract_files(zip_f, cur_path): with zipfile.ZipFile(zip_f, 'r') as zip_file: zip_file.extractall(cur_path) def rename_files(cur_path): for files in os.listdir(cur_path): new_name = get_new_name(files) os.rename(os.path.join(cur_path, files), os.path.join(cur_path, new_name)) def main(): files = [f for f in FILES_IN_CUR_DIR if f.endswith('.zip')] for f in files: cur_path = os.path.join(CUR_DIR, f[:-4]) print('Extracting ' + f) extract_files(f, cur_path) print('Started renaming') rename_files(cur_path) print('Removing zip file ', f) os.remove(os.path.join(CUR_DIR, f)) print('Writing back to ' + f) shutil.make_archive(cur_path, 'zip', cur_path) print('\n')if __name__ == "__main__": main()
This is just the first version that I used to get it to work. It creates temporary folders that I needed to delete but that was just one select and delete. Not a big thing. I plan to take care of the temporary folders too. The new one you can find in my github -> general -> Python33 -> Utilities maybe in a few days.