30.12.2017 г.

Calculate size of folder with python scripts only folder not RAR

#Import module
import os
import sys

class InFolder:

    def __init__(self, folder):
        self.folder = folder

    def search(self):
        founded = set()
        for root, dirname, filename in os.walk(self.folder):
            clean_root = os.path.normpath(root)
            clear_root_name = os.path.normcase(clean_root)
            founded.add(clear_root_name)
        founded.remove(self.folder)
        return founded


if len(sys.argv) == 1:
        print("Try again with add path to scan!")
        sys.exit('Usage: python %s path-name' % sys.argv[0])
elif not os.path.exists(sys.argv[1]):
    print("Try again with add path to scan!")
    sys.exit('Usage: python %s and corect file name (example c:\\)' % sys.argv[0])
    sys.exit()
else:
    my_project = InFolder(sys.argv[1])
    clear_folder = my_project.search()


class Second:

    def __init__(self, path2):
        self.path2 = path2

    def calculate_size(self):
        my_calc = dict()
        size = 0
        for root, dirname, filename in os.walk(self.path2):
            for file in filename:
                f_path = os.path.join(root, file)
                size += os.path.getsize(f_path)
            my_calc[self.path2] = (size/1024)/1024
        return my_calc


total = dict()

for f in clear_folder:
    main = Second(f)
    for i, v in main.calculate_size().items():
        total[i] = v

for line in sorted(total.items(), key=lambda x: x[1]):
    print('{0:>10} - {1:.2f}Mb'.format(*line))

16.12.2017 г.

Read excell file with python, validate and return defaultdict

import os
import xlrd
from collections import defaultdict
import sys
from pprint import pprint
import re

'''
Some name1     2345        someemal1@gmail.com
Some name12    23456        someemal2@gmail.com
Some name1    0            someemal1@gmail.com
Some name3    0889345        someemal1@gmail.com
'''

filename = "somefile.xls"
result = defaultdict(list)


def checkFilename(filename):
    '''Check file is excel or not '''
    if filename.endswith('xls'):
        return filename
    else:
        return 'Not valid filename'
        sys.exit()


class ReadXLS:

    def __init__(self, checkFilename):
        self.filename = checkFilename

    def realReadFilename(self):
        '''Read xls file with xlrd module '''
        try:
            workbook = xlrd.open_workbook(self.filename)
        except:
            print("some error...")
            sys.exit()
        else:
            try:
                sheet = workbook.sheet_by_index(0)
            except IndexError as ie:
                print(ie)
                sys.exit()
            else:
                for rowx in range(sheet.nrows):
                    columnmapping = sheet.row_values(rowx)
                    yield columnmapping

    def checkResult(self):
        '''add to result only what i whant'''
        for line in ReadXLS.realReadFilename(self):
            if ((line[0] in (None, '')) or (line[1] in (None, ''))
                    or (line[2] in (None, '')) or not
                    re.search(r'[\w.-]+@[\w.-]+.\w+', line[2])):
                continue
            else:
                #result[line[2].upper()].append((line[0], line[1]))
                result[line[2].upper()].append(
                    (line[1].strip().replace(' ', ''), line[0].strip())
                )

    def __repr__(self):
        ''' Why I can '''
        return "{}".format(self.filename)


if __name__ == '__main__':
    test = ReadXLS(checkFilename(filename))
    test.checkResult()
    pprint(result)

24.09.2017 г.

Python compare data from sqlite database is between two date

#import module
import sqlite3

#database path is here
database = 'test.db'

#Testing in the data
#25.09.2017 27.09.2017
#01.10.2017 03.10.2017

class db_conn:
    ''' Class connect main '''
    def __init__(self, db, Fdata=None, Sdata=None):
        self.db = db
        self.Fdata = Fdata
        self.Sdata = Sdata
        self.con = sqlite3.connect(self.db)

    def insert(self):
        ''' insert into database two value's '''
        self.con.execute("INSERT INTO praznik (Fdata, Sdata) VALUES (?, ?)", (self.Fdata, self.Sdata))
        self.con.commit()
        self.con.close()


    def show_table(self):
        ''' Use for select from database '''
        self.cur = self.con.cursor()
        self.cur.execute("SELECT * from praznik")
        for row in self.cur:
            print("First Data {fdata} - Second Data {sdata}".format(fdata=row[1], sdata=row[2]))
        self.con.close()


    def check_period(self, fdata_check, ldata_check):
        ''' check period is valid or not '''
        self.fdata_check = fdata_check
        self.ldata_check = ldata_check
        self.cur = self.con.cursor()
        self.cur.execute("SELECT * from praznik")
        for row in self.cur:
            if row[1] <= self.ldata_check and row[2] >= self.fdata_check:
                print("Problem")
                break
            else:
                print("Look Good")
                break
        self.con.close()

3.09.2017 г.

Python use picke to write json to faile and read back to dictionary

#import module
from pprint import pprint  # pretiprint
import json
import os
import pickle
# hard code param
test_file = 'test_file.json'
db = {}
dl = {}

def check_file_exists(filename):
    ''' Check file exists or not '''
    if not os.path.exists(filename):
        open(filename, 'w').close()

def write_in_json(filename, db):
    ''' Write dictionary to file with ekstension json'''
    db = json.dumps(db)
    with open(filename, 'wb') as f:
        pickle.dump(db, f)

def load_from_json_file(filename, dl):
    ''' Load serial object into file to dictionary '''
    json_file = open(filename, 'rb')
    dl = pickle.load(json_file)
    dlj = json.loads(dl)
    return dlj

# Get from enywere for test
borko = {'name': 'Borko', 'ip': '192.168.168.1', 'df': 30000, 'free': 'dev'}
sue = {'name': 'Sue Somebody', 'ip': '192.168.168.2', 'df': 40000, 'free': 'hdw'}
tom = {'name': 'Tom Aks', 'ip': '192.168.168.3', 'df': 0, 'free': None}

db['bob'] = borko
db['sue'] = sue
db['tom'] = tom
if __name__ == '__main__':
    # Create file if not exists uncoment to begin
    # check_file_exists(test_file)
    # function write json to file uncoment to begin
    #write_in_json(test_file, db)
    # fuction load picke file to json object return to dictionary
    #print(load_from_json_file(test_file, dl))

14.08.2017 г.

Replace empty space in name with python script

Path = r'C:\Users\Borko - Home\Desktop\TEST\trii'
search_patter = ' '
import os
log_file = 'changes.log'

class Main:

    def __init__(self, Path, search_patter):
        self.Path = Path
        self.search_patter = search_patter
        ''' check if file exists only for me'''
        assert os.path.exists(self.Path) == True

    def search_for_file(self):
        result = []
        for root, firname, filename in os.walk(self.Path):
            for file in filename:
                if self.search_patter in file:
                    result.append(root + '\\' + file)
        return result

    def write_to_log_file(self):
        with open(log_file, 'w') as f:
            for file in Main.search_for_file(self):
                f.write(file + '\n')

    def change_fileName(self):
        for file in Main.search_for_file(self):
            new_filename = os.path.basename(file).replace(' ', '_')
            new_path_name = os.path.dirname(file)
            total_new = new_path_name + '\\' + new_filename
            os.rename(file, total_new)

if __name__ == "__main__":
    progress = Main(Path, search_patter)
    progress.change_fileName()

2.08.2017 г.

Generate random password and send to email with python

#IMOPORT MODULES
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#HARDCORE NAME AND EMAIL
list_with_names = {"First Name": "first_email@abv.bg", "Second Name": "second_email@abv.bg"}
sender = 'unrealborko@gmail.com'
#FUCNTION GENERATE PASSWORD'S
def generate(name):
    choice = "a#@bcdeb1234567890ABCDFEGH"
    ask = random.sample(choice, 8)
    forma = [['@', '#', '!'], [i for i in ('abcdfegh')], [i for i in ('ABCDFEGH')], [i for i in ('1234567890')]]
    while (any(z in forma[0] for z in [i for i in ask])
         and any(z in forma[1] for z in [i for i in ask])
          and any(z in forma[2] for z in [i for i in ask])
        and any(z in forma[3] for z in [i for i in ask])) != True:
        ask = random.sample(choice, 8)
       
    return("Password for {} is {}".format(name, "".join(ask)))

#FUNCTION TO SEND PASSWORD TO NAME EMAIL
def sendmail(from_email, to_addr, subject, message, login, password, name, smtpserver = "smtp.gmail.com", smtpport = 587):
    from_email = from_email
    to_addr = to_addr
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_addr
    msg['Subject'] = subject
    passsfare = generate(name)
    body = "{}".format(passsfare)
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login, password)
    text = msg.as_string()
    server.sendmail(from_email, to_addr, text)
    server.quit()
#FUNCTION APPLY PASSWORD TO NAME
def password_to_name():
    for name, email in list_with_names.items():
        sendmail(from_email = "sender email is here",
            to_addr = email,
            subject = "Password for {}".format(name),
            message = "This is a password",
            login = "borkounreal@gmail.com",
            password = "userpassword is here!!!!!1",
            name = name)
        #print(generate(name))

if __name__ == "__main__":
    password_to_name()

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)