Created
August 28, 2020 17:28
-
-
Save mshiyaf/1db4c85a07fb9c87fcf1d57a0fb5a55e to your computer and use it in GitHub Desktop.
Python script to convert a folder to tar file and replace file only if changes occur.
This file contains hidden or 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
#!/Users/mshiyaf/.pyenv/shims/python | |
import os | |
import tarfile | |
import time | |
def tardir(path,tar_name): | |
tar_log = open('/Users/mshiyaf/Code/backup_mod.log','w') | |
try: | |
with tarfile.open('/Users/mshiyaf/Code/Texol_Backup.tar','r') as tar: | |
file_name_array = [] | |
file_time_array = [] | |
tar_name_array = [] | |
tar_time_array = [] | |
for root, dirs, files in os.walk(path): | |
for file in files: | |
node_mod = 'node_modules' | |
if(node_mod not in root): | |
file_name_array.append(os.path.join(root,file)) | |
file_time_array.append(os.path.getmtime(os.path.join(root,file))) | |
for filename in tar: | |
tar_name_array.append(filename.name) | |
tar_time_array.append(filename.mtime) | |
if file_name_array == tar_name_array: | |
for i in range(len(file_name_array)): | |
if file_time_array[i] != tar_time_array[i]: | |
with tarfile.open(tar_name,'a') as tar_add: | |
time_of_mod = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_time_array[i])) | |
print(file_name_array[i]+'-------------'+time_of_mod,file=tar_log) | |
tar_add.add(file_name_array[i]) | |
create_new_tar(path,tar_name) | |
else: | |
create_new_tar(path,tar_name) | |
except Exception as e: | |
error_log = open('/Users/mshiyaf/Code/error.log','w') | |
print(e,file=error_log) | |
create_new_tar(path,tar_name) | |
def create_new_tar(path,tar_name): | |
log = open('/Users/mshiyaf/Code/backup.log','w') | |
with tarfile.open(tar_name,'w') as tar_handle: | |
for root, dirs, files in os.walk(path): | |
for file in files: | |
node_modules = 'node_modules' | |
if (node_modules not in root): | |
time_of_mod = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(os.path.join(root,file)))) | |
time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) | |
print(root+'------'+file+'-------'+time_now+'------'+time_of_mod,file=log) | |
tar_handle.add(os.path.join(root, file)) | |
tardir('/Users/mshiyaf/Texol','Texol_Backup.tar') | |
tardir('/Users/mshiyaf/Sites','Sites_Backup.tar') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment