10.06.2017 г.

Tkinter search for file, delete, copy or move them

from tkinter import *
from tkinter import filedialog
import os
import sys
from shutil import copyfile, move

#ASK FOR OPEN BEGIN DIRECTORY
def open_begin_foldert(event=None):
  Begin_Folder =  filedialog.askdirectory(title = "Select begin directory")
E_name.delete(END, 0)
    E_name.insert(0, Begin_Folder)

#ASK FOR OPEN SEARCH DIRECTORY
def open_search_foldert(event=None):
  End_Folder =  filedialog.askdirectory(title = "Select search directory")
E_name_destination.delete(END, 0)
E_name_destination.insert(0, End_Folder)

#GET BEGIN, END DIRECTORY AND PARRET FOR SEARCH
def show_result():
  Begin_Folder = E_name.get()
End_Folder = E_name_destination.get()
patter = E_patern.get()
return ((Begin_Folder, End_Folder, patter))

#--------------------START WITH SEARCH FUNTION'S ---------------
#FUNCTION USE FOR SEARCH PATTER USED IN M_SEARCH FUNCTION UNDER
def search_pattern(patter, Begin_Folder, End_Folder):
  for root, dirname, filename in os.walk(Begin_Folder):
for file in filename:
if file.endswith(patter) and (root != End_Folder):
total_path = root+'/'+file
head, tail = os.path.split(total_path)
  L.insert(END, root+"/"+file)

#SEARCH FUNCTION ADD TO BUTTON SEARCH!
def m_search():
  Begin_Folder, End_Folder, patter = show_result()
search_pattern(patter, Begin_Folder, End_Folder)
#--------------------END WITH SEARCH FUNTION'S ---------------

#--------------------START WITH COPY FUNTION'S ---------------
def copy_pattern(patter, Begin_Folder, End_Folder):
  for root, dirname, filename in os.walk(Begin_Folder):
for file in filename:

if file.endswith(patter) and (root != End_Folder):
                counter = 0
total_path = root+'/'+file
head, tail = os.path.split(total_path)
try:
copyfile(total_path, End_Folder+"/"+tail)
counter += 1
print("Now copy file", self.End_Folder+"/"+tail)
except:
print("File {} exists or somthing wrong with copy!".format(End_Folder+"/"+tail))
  L.insert(END, "Copy was {} file's".format(counter))


def m_copy():
  Begin_Folder, End_Folder, patter = show_result()
  copy_pattern(patter, Begin_Folder, End_Folder)

#--------------------END WITH COPY FUNTION'S ---------------

#--------------------START WITH MOVE FUNTION'S ---------------
def move_pattern(patter, Begin_Folder, End_Folder):
    counter = 0
  for root, dirname, filename in os.walk(Begin_Folder):
for file in filename:
if file.endswith(patter) and os.path.isdir(End_Folder):
total_path = root+'/'+file
head, tail = os.path.split(total_path)
try:
move(total_path, End_Folder+"/"+tail)
counter += 1
print("Move file", End_Folder+"/"+tail)
except:
print("somthing wrong with copy {}!".format(End_Folder+"/"+tail))
    L.insert(END, "Move was {} file's".format(counter))

def m_move():
  Begin_Folder, End_Folder, patter = show_result()
move_pattern(patter, Begin_Folder, End_Folder)
#--------------------END WITH MOVE FUNTION'S ---------------

#--------------------START WITH DELETED FUNTION'S ---------------
def delete_pattern(patter, Begin_Folder, End_Folder):
    counter = 0
  for root, dirname, filename in os.walk(Begin_Folder):
for file in filename:
if file.endswith(patter) and (root != End_Folder):
total_path = root+'/'+file
head, tail = os.path.split(total_path)
try:
os.remove(total_path)
counter += 1
print("Remove file", End_Folder+"/"+tail)
except:
print("somthing wrong with copy {}!".format(End_Folder+"/"+tail))
    L.insert(END, "Deleted {} file's".format(counter))

def m_deleted():
  Begin_Folder, End_Folder, patter = show_result()
delete_pattern(patter, Begin_Folder, End_Folder)

#-------------------END WITH DELETED FUNTION'S ---------------

#TKINTER CONFIGURATION
root = Tk()
root.title("File search or delete")
root.resizable(0,0)
root.geometry("400x450+100+100")


#LABEL's
L_name = Label(root, text="Search_folder")
L_name.grid(row=0, column=0, sticky=W)

L_dest_name = Label(root, text="Destination_folder")
L_dest_name.grid(row=1, column=0)

L_pattern = Label(root, text="Entry pattern")
L_pattern.grid(row=2, column=0, sticky=W)

#ENTRY's
E_NAME_VALUE = StringVar(root)
E_name = Entry(root, textvariable=E_NAME_VALUE)
E_name.grid(row=0, column=1)
E_name.bind('<Button-1>', open_begin_foldert)

E_name_destination = Entry()
E_name_destination.grid(row=1, column=1)
E_name_destination.bind('<Button-1>', open_search_foldert)

E_patern = Entry()
E_patern.grid(row=2, column=1)

#BUTTON's
B_search = Button(root, text="Search", command=m_search)
B_search.grid(row=0, column=2)

B_copy = Button(root, text="Copy", command=m_copy)
B_copy.grid(row=0, column=3)

B_move = Button(root, text="Move", command=m_move)
B_move.grid(row=1, column=3)

B_delete = Button(root, text="Delete", command=m_deleted)
B_delete.grid(row=1, column=2)

#SCROLLBAR
yScroll = Scrollbar(root,orient=VERTICAL)
yScroll.grid(row=3, column=6, sticky=N+S)
#LABEL IS UNDER!

L = Listbox(root, height=20)
L.grid(row=3, column=0, sticky=N+S+E+W, columnspan=5)
L.config(yscrollcommand=yScroll.set)
yScroll.config(command=L.yview)




#Begin the magic!!!
if __name__ == "__main__":
    root.mainloop()

9.06.2017 г.

read file and search some text in file (use chunk size)

#import module sys for get param and exit if param not exists and os for
#check if ifle exists

import sys
import os

#check param is corect when start program in prompt
if len(sys.argv) != 3:
    print("Enter file name and what search in file ")
    sys.exit()
else:
    File_Name = sys.argv[1]
    search_name = sys.argv[2]
#write how much char read when read file name
    line_len = 10


class Main:

    def __init__(self, File_Name):
        self.File_Name = File_Name
        if os.path.isfile(self.File_Name):
            self.read_file_name = open(self.File_Name).read()
            Main.read_file(self, self.read_file_name, line_len)
        else:
            print("File not found")
            sys.exit()

    def read_file(self, name_file, line_len):
        lines = self.read_file_name.split('\n')
        while lines:
            chunk = lines[:line_len]
            lines = lines[line_len:]
            for line in chunk:
                if line.startswith(search_name) or line.startswith(search_name.upper()):
                    print(line)


if __name__ == "__main__":
    main = Main(File_Name)

3.05.2017 г.

Firebird database backup script

  #!/bin/bash

#Below I change to 1 if I want to send the archive and not an email
#CHANGE AND PARAM FOR LOGIN
FTP_STATUS=0
FTP_USER=
FTP_PASSWORD=
FTP_URL=
#tuka ima nqkakava izmama shto ne moga da dobavq papkata kym patq
#zatova dobavqm i dolnoto
FTP_FOLDER=

#Hardcode param
#FB COMMON
USERNAME=SYSDBA
PASSWORD=masterkey
RUN=/opt/firebird/bin/gbak

#PATH PARAM
#PATH TO DATABASE
DATA_BASE=/home/username/database/FDB.FDB
FILE_NAME="${DATA_BASE##*/}"

#PATH TO BACKUP FOLDER
BACKUP_FOLDER=/home/username/backup

#ATTACH DATA AND TIME TO ARHIVE
DATA_TIME=`date +%d-%m-%Y-%H-%M`

#CONCAT FILE WITH DATA TIME
CREATE_BACKUP=${FILE_NAME%%.*}-$DATA_TIME.FBK

#USER FRANDLY TAR ARHIVE
ZIP_FILE_BACKUP=${CREATE_BACKUP%%.*}.tar.gz
#HOW MUCH ARCHIVE SAVE
SAVE=3

#CHECK IF FOLDER EXISTS AND CHANGE OWNER

if [ ! -d $BACKUP_FOLDER ];then
mkdir -p $BACKUP_FOLDER && chown -R firebird.firebird $BACKUP_FOLDER
else
chown -R firebird.firebird $BACKUP_FOLDER
fi

#MAKE BACKUP AND THEN CREATE ZIP FILE FROM ARHIVE THEN ARHIVE DELETED
$RUN -g -t -user $USERNAME -password $PASSWORD $DATA_BASE $BACKUP_FOLDER/$CREATE_BACKUP
`tar -czf $BACKUP_FOLDER/$ZIP_FILE_BACKUP $BACKUP_FOLDER/$CREATE_BACKUP`
`ls -d -1tr $BACKUP_FOLDER/* | grep FBK$ | head -n1 | xargs rm -rf`

#CHECK HOW MUCH ARCHIVE HAVE AND DELETE IF BIGGER THEN SAVE OARAM

if [ $(ls -d -1tr $BACKUP_FOLDER/* | grep tar.gz$ | wc -l) -gt $SAVE ];then
`ls -d -1tr $BACKUP_FOLDER/* | grep tar.gz$ | head -n1 | xargs rm -rf`
fi

if [ $FTP_STATUS -eq 1 ];then
cd $BACKUP_FOLDER &&
FTP_FILE=`ls -1t | head -n1`

ftp -inv $FTP_URL <<EOF
user $FTP_USER $FTP_PASSWORD
cd $FTP_FOLDER
put $FTP_FILE
bye
EOF
fi

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)