Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Syncronize content of files across directories, keeping the most up-to-date edits
# Syncronize files across directories, keeping the most up-to-date edits
lists = [
'directory_1/list_of_terms.yaml',
'directory_2/list_of_terms.txt'
]
list_items = {} # Form: [item] = [time(integer), keep(boolean)]
# Generate full list of single_listed items (stores all possible terms)
for single_list in lists:
with open(single_list, 'r') as f:
for row in f:
list_items[row.strip()] = [0, True]
# Sync lists, identifying whther to keep each item
for single_list in lists:
last_update = os.stat(single_list).st_mtime # Last time file edited
current_list = {} # Dictionary to keep track of last updated time
# Generate dict from current list
with open(single_list, 'r') as f:
for row in f:
current_list[row.strip()] = [last_update, True]
# Iterate over all items to determine if we should utilize that
for item in list_items:
# Only keep the most recent updated item
if last_update > list_items[item][0]:
keep_item = True # Default, keep items
if item not in current_list:
keep_item = False # Mark for deletion
list_items[item] = [last_update, keep_item]
# Rewrite all the files to have the master list
for single_list in lists:
with open(single_list, 'w') as f:
for item in list_items:
if list_items[item][1]: # Marked for saving the term
f.write(item + "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.