Показват се публикациите с етикет python delete file. Показване на всички публикации
Показват се публикациите с етикет python delete file. Показване на всички публикации

8.02.2017 г.

Find archive and extract in folder

import os
import pyunpack

class Main:
  def __init__(self, PATH, razshirenie):
self.PATH = PATH
self.razshirenie = razshirenie

def search(self):
for files in os.listdir(self.PATH):
if files.endswith(self.razshirenie):
yield self.PATH+'\\'+files

  def show_me(self):
for result in Main.search(self):
pyunpack.Archive(result).extractall(PATH)
#print (result)


if __name__ == "__main__":
  main = Main(PATH, 'rar')
main.show_me()

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)

12.09.2016 г.

Show image, with options to resize it.

 #IMPORT SOME MODULE NEED pip install pillow  
 #if not esists  
 import os, sys, Tkinter  
 from PIL import Image, ImageTk  
 #FIRST GLOBAL PARAM TO PATH  
 #USES Pictures folder of user that run script  
 PIC = os.path.expanduser('~')+"\Pictures"  
 #CALCULATE RESULT IS HERE  
 list_with_pic = []  
 old_label_image = None  
 #FUNCTION CLOSE PICTURE WHEN PUSH LEFT MOUSE BOTTON  
 def button_click_exit_mainloop (event):  
   """FUNCTION CLOSE PICTURE WHEN PUSH LEFT MOUSE BOTTON"""  
   event.widget.quit() # this will cause mainloop to unblock.  
 #THIS SEARCH FOR PICTURES IN PIC FOLDER  
 #RETURN ABSOLUTE PATH  
 def search_picture(PATH):  
   """THIS SEARCH FOR PICTURES IN PIC FOLDER / RETURN ABSOLUTE PATH"""  
   for root_p, dirname, filename in os.walk(PATH):  
     for file in filename:  
       if file.endswith(("jpg","png")):  
         yield os.path.join(root_p, file)  
 #RETURN RESULT SPARES MEMORY  
 def return_orig():  
   """RETURN RESULT SPARES MEMORY"""  
   for result in search_picture(PIC):  
     yield result  
 #SHOW PICTURES USE TKINTER TO VISUALIZE  
 def show_pic():  
   """SHOW PICTURES USE TKINTER TO VISUALIZE"""  
   len_of_pictures = [] #CALCULATE RESULT  
   for m in return_orig():  
     len_of_pictures.append(m)  
   print ""  
   #PRINT TOTAL LEN OF FOUND PICTURE'S  
   print "The total len of pictures is {}".format(len(len_of_pictures))  
   print ""  
   #ASK TO OPEN PICTURE FOR VIEW OR NOT, TKINTER CLOSE WHEN HIT N/n or somthing else  
   ask = raw_input("Do you want to open all image's : Y or N _\b" )  
   if ask == 'Y' or ask == 'y':  
     root = Tkinter.Tk()  
     root.bind("<Button>", button_click_exit_mainloop)  
     root.geometry('+%d+%d' % (200,200))  
     for root_d, dirname, filename in os.walk(PIC):  
         for file in filename:  
           if file.endswith(("jpg","png")):  
             list_with_pic.append(os.path.join(root_d, file))  
     for result in list_with_pic:  
       #OPEN IMAGE  
       image1 = Image.open(result)  
       #ORIGINAL GEOMETRY IS HERE TAKE FROM IMAGE  
       root.geometry('%dx%d' % (image1.size[0],image1.size[1]))  
       tk_pik = ImageTk.PhotoImage(image1)  
       #LABEL IS HERE SHOW IN TOP OF THE TKINTER CANVAS  
       label_image = Tkinter.Label(root, image=tk_pik)  
       #PLACE TO POSITION  
       label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])  
       root.title(result)  
       if old_label_image is not None:  
         old_label_image.destroy()  
       odl_lavel_image = label_image  
       root.mainloop()  
   #IF ASK IS N/n exit from program  
   elif ask == 'N' or ask == 'n':  
     print "Refused by the user"  
     sys.exit()  
   else:  
     sys.exit()  
 #THIS USE TO RESIZE A PICTURE'S  
 def resize_pic():  
   """THIS USE TO RESIZE A PICTURE'S"""  
   if os.path.exists(PIC):  
     TUMBNAILS = "thumbnail"  
     if os.path.exists(PIC+'\\'+TUMBNAILS):  
       TUMBNAILS = PIC+'\\'+TUMBNAILS  
     else:  
       os.makedirs(PIC+'/'+TUMBNAILS)  
       TUMBNAILS = PIC+'\\'+TUMBNAILS  
   #ASK TO USER PUSH WIDTH AND HEIGHT OF THUMBNAIL  
   width = raw_input("Enter width :")  
   height = raw_input("Enter height :")  
   for result in return_orig():  
     image = Image.open(result)  
     image = image.resize((int(width), int(height)), Image.ANTIALIAS)  
     image.save(TUMBNAILS+'\\'+result.split('\\')[-1], 'jpeg', quality=90)  
 def ask_for_what():  
   print "-------------------------------------------"  
   print "1 - For list pictures with original size -"  
   print "2 - Corect pictures to tumbnails     -"  
   print "-------------------------------------------"  
   answer = raw_input('Choice whant you want :')  
   print ""  
   print "You choice {answer}".format(answer=answer)  
   if answer == '1':  
     show_pic()  
   elif answer == '2':  
     resize_pic()  
   else:  
     "???"  
 if __name__ == "__main__":  
   print "Default path is {path}".format(path=PIC)  
   print ""  
   PIC = raw_input("Enter for Default or write absolute path to pictures :")  
   if PIC == "":  
     PIC = os.path.expanduser('~')+"\Pictures"  
   else:  
     PIC = PIC  
   ask_for_what()  

26.03.2015 г.

Python script for search file type with options for deleted them

#########################################

#  Script uses for deleted searched with#

#         extension file!!              #

#########################################

# --*-- coding: utf-8 --*--


import os, argparse, time


# parser = argparse.ArgumentParser(description='Process for deleted file')

# parser.add_argument('integers', metavar='N', type=int, nargs='+',

#                    help='an integer for the accumulator')

# args = parser.parse_args()

# print(args.accumulate(args.integers))


#Asking for Begin Dirname and search type


dirname = raw_input("Enter dirname from begin :")

Ending = raw_input("Enter exsension for deleted :")

acumulate_result = []   #Use for acumulate result if whant to deleted it


def Searc_Torrent(dirname):


 """Function use for search file with

 with help module os.walk"""

    if os.path.isdir(dirname) and os.path.exists(dirname):

        for root, path, filename in os.walk(dirname):

            for fn in filename:

                 if fn.endswith(Ending):

                    yield os.path.join(dirname,fn)

     else:

        print "\n%s is not looking by folder" % dirname


    

def show_torrent():


 """Function use for show result and add them to list

 with name acumulate_result"""

    begin = time.time()

    for f in Searc_Torrent(dirname):

         print f

    acumulate_result.append(f)

     ending = time.time()

    print "Search finish with %s secund's" % (ending-begin)



def delete_result():


 """Function use for delete result"""

    for deleted in acumulate_result:

        yield deleted



if __name__ == "__main__":

 show_torrent()

 queston = raw_input("Do you whant to delete result ? (Y/N) :")

 if queston.lower() == 'y':
    print "Deleted"

    for deleted in delete_result():

        os.unlink(deleted)


 elif queston.lower() == 'n':

        print "Good bye"

 else:
     print "Good bye with wron answer!!!"