Created
February 22, 2022 21:22
-
-
Save robince/02f7613511b27279f9d661971ff880b7 to your computer and use it in GitHub Desktop.
Fix loss of folder "date modified" on mac (e.g. from iCloud): cd ~/Documents; set_folder_date_modified.py ./
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import sys | |
import time | |
from datetime import datetime | |
def set_folder_dates(root): | |
for x in os.walk(root, topdown=False): | |
set_folder_date(*x) | |
def remove_ds_store(files): | |
return [f for f in files if f != '.DS_Store'] | |
def set_folder_date(folder, subfolders, files): | |
# don't look at .DS_Store | |
files = remove_ds_store(files) | |
# empty folders date is lost | |
# only consider subfolders with a file somewhere in their tree | |
subfolders_with_files = [] | |
for subfolder in subfolders: | |
for _, _, subfiles in os.walk(os.path.join(folder, subfolder)): | |
subfiles = remove_ds_store(subfiles) | |
if len(subfiles) > 0: | |
break | |
else: | |
# if no files found then don't add | |
continue | |
subfolders_with_files.append(subfolder) | |
date_source = [path for f in subfolders_with_files + files | |
if os.path.exists(path := os.path.join(folder, f))] | |
if len(date_source) == 0: | |
return | |
# filter out corrupt files with modified date in the future | |
mtimes = [mtime for f in date_source | |
if (mtime := os.path.getmtime(f)) < time.time()] | |
if len(mtimes) == 0: | |
return | |
newest = max(mtimes) | |
stat = os.stat(folder) | |
date = datetime.fromtimestamp(newest) | |
print(f"Setting {folder} date to {date.strftime('%d/%m/%Y, %H:%M:%S')}") | |
os.utime(folder, (stat.st_atime, newest)) | |
if __name__ == '__main__': | |
set_folder_dates(sys.argv[1]) |
I got to this page from Stack Overflow. Thanks so much for sharing the Python solution. Works great!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! So handy, worked perfectly on the root folder I was looking to fix, all the way down to every folder inside.