8.01.2017 г.

Search for file's with some extension and add file's to archive

#Import some modules
import os #for search os.walk
from fnmatch import fnmatchcase                       #for search extend for file (capitalize)
from datetime import datetime                            #for found date and time
from zipfile import ZipFile #for create archive
from os.path import basename #for return base name from abs path to file
import sys #get arguments
#--------------------------------------------------------------------------

#!!! IF ADD ARGUMENT INTO START SCRIPT PATH
#--- AND FILE_EX GET FROM ARGS IN FORMAT
#--- ELSE USE DEFAULT PATH AND EX !!!

if len(sys.argv) < 2:
  Folder_name = "."
file_ex = "*.txt"
else:
  Folder_name = sys.argv[1]
file_ex = sys.argv[2]


#Found date and time now
d = str(datetime.now()).split(".")[0]

#Return date into my readable string
d = (datetime.strptime(d, "%Y-%d-%m %H:%M:%S"))

#Return date and time into format you want
date_for_archive = (datetime.strftime(d, "%d-%m-%Y_%H-%m"))



def search_for_file(DirName, file_extend):
"""Search for file with extend with file_extend
  return absolute path to file if search is return result True """
for root, dirname, filename in os.walk(DirName):
for file in filename:
if fnmatchcase(file, file_extend):
yield os.path.join(root, file)



def arr_result_to_archive():
"""Add found file's into archive with name from
archive_name, the name has date and time
"""
  archive_name = ZipFile(date_for_archive+".zip", 'w')
for result in search_for_file(Folder_name, file_ex):
archive_name.write(result, basename(result))
#--Uncomend second row and coment above if want to add
#--file with absolute path to archive
#archive_name.write(result)
    archive_name.close()


if __name__ == "__main__":
  arr_result_to_archive()


# For read zip archive uncoment second row in new file
# file = ZipFile("01-08-2017_20-08.zip", 'r')
# for i in file.infolist():
# print (i)

Няма коментари :

Публикуване на коментар