Приложение к «Python в библиотеке» — страница 4 из 7

del_empty_dir.py

#!/bin/env python

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

# Удаление пустых папок

import sys, os

def del_empty_dirs(path):

, ,global co

, ,for d in os.listdir(path):

, , , ,a = os.path.join(path, d)

, , , ,if os.path.isdir(a):

, , , , , ,del_empty_dirs(a)

, , , , , ,if not os.listdir(a):

, , , , , , , ,co += 1

, , , , , , , ,os.rmdir(a) , , , , , ,

# ------------------------------ , , , , , ,

Mpath = os.getcwd()

co = 0

del_empty_dirs(Mpath)

print('Удалено '+str(co)+' пустых папок.')

Mer.py

#!/usr/bin/env python

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

# поиск одинаковых файлов

#

import sys, os

import hashlib #

ex = 'zip'#'fb2'#'txt'#'mp4'#'gif'#'jpg'

GFiles = []

co = 0

LOut = []

def SaveInList(L3):

, ,if len(L3) > 0:

, , , ,global co

, , , ,global LOut

, , , ,for i in L3:

, , , , , ,LOut.append(i+'\n')

, , , , , ,co += 1

, , , ,LOut.append('-----\n\n')

def ScanMd5(L2):

, ,if len(L2) > 0:

, , , ,L3 = []

, , , ,L2.sort()

, , , ,flag = False

, , , ,oldMd5 = ''

, , , ,OldFile = ''

, , , ,for i in L2:

, , , , , ,m = i.split('%')

, , , , , ,ZMd5= m[0]

, , , , , ,if (not flag) and (ZMd5 == oldMd5):

, , , , , , , ,flag = True

, , , , , , , ,L3.append(OldFile)

, , , , , ,if flag:

, , , , , , , ,if ZMd5 == oldMd5:

, , , , , , , , , ,L3.append(m[1])

, , , , , , , ,else:

, , , , , , , , , ,flag = False

, , , , , , , , , ,SaveInList(L3)

, , , , , , , , , ,L3.clear()

, , , , , , , , , ,

, , , , , ,oldMd5 = ZMd5

, , , , , ,OldFile = m[1]

, , , ,SaveInList(L3) #

, ,

def ScanSize(GFiles):

, ,if len(GFiles) > 0:

, , , ,L = []

, , , ,flag = False

, , , ,oldSize = ''

, , , ,OldFile = ''

, , , ,for i in GFiles:

, , , , , ,m = i.split('%')

, , , , , ,Zaize = m[0]

, , , , , ,if (not flag) and (Zaize == oldSize):

, , , , , , , ,flag = True

, , , , , , , ,L.append(getmd5(OldFile)+'%'+ OldFile)

, , , , , ,if flag:

, , , , , , , ,if Zaize == oldSize:

, , , , , , , , , ,L.append(getmd5(m[1])+'%'+ m[1])

, , , , , , , ,else:

, , , , , , , , , ,flag = False

, , , , , , , , , ,ScanMd5(L)

, , , , , , , , , ,L.clear()

, , , , , , , , , , , ,

, , , , , ,oldSize = Zaize

, , , , , ,OldFile = m[1]

, , , ,ScanMd5(L) #

#--------------------------------------------------

def getmd5(file_name):

## try

with open(file_name, "rb" ) as file_to_check:

data = file_to_check.read()

return hashlib.md5(data).hexdigest()

def parse_file(fn):

, ,global GFiles

, ,s=str(os.path.getsize(fn))+'%'#

, ,GFiles.append(s+fn)

, , , ,

def parse_dir(sSrc):

, ,global f_list

, ,for file in os.listdir(sSrc):

, , , ,# full pathname

, , , ,file=os.path.join(sSrc,file)

, , , ,if os.path.isdir(file):

, , , , , ,parse_dir(file)

, , , ,else:

, , , , , ,m = file.split('.')[-1] # извлечение расширения

, , , , , ,m = m.lower()

, , , , , ,if (m == ex):

, , , , , , , ,parse_file(file)

, , , , , , , ,

#--------------------------------------------------

path = os.getcwd()

parse_dir(path)

GFiles.sort()

ScanSize(GFiles) #

if co > 0:

f = open('merg_'+ex+'.txt', 'w')

for i in LOut:

, , f.write(i+'\n')

f.close()

print('Done '+ex+' -> '+str(co))

same_fb2.py

#!/bin/env python

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

import sys, os

from m_list import FindValue, PrintList, Books

list = []

def fb2zip(pa):

, ,p = pa.split('/')

, ,FindValue(p[-1],pa)

# -----------------

def GetListFiles(PathForWork):

, ,global list

, ,for file in os.listdir(PathForWork):

, , , ,path = os.path.join(PathForWork, file)

, , , ,ex = path.split('.')

, , , ,if not os.path.isdir(path): #

, , , , , ,if ex[-1].lower() == 'fb2':

, , , , , , , ,fb2zip(path)

, , , , , ,else:

, , , , , , , ,e = ex[-2]+ex[-1]

, , , , , , , ,if e.lower() == 'fb2zip':

, , , , , , , , , ,fb2zip(path)

, , , ,else: #

, , , , , ,GetListFiles(path) #

# -----------------

def CompareList():

, ,OldFile = ''

, ,OldPath = ''

, ,flag = False

, ,for it in Books:

, , , ,if (it[0] == OldFile):

, , , , , ,if not flag :

, , , , , , , ,flag = True

, , , , , , , ,list.append(OldPath)

, , , , , ,list.append(it[1])

, , , ,else:

, , , , , ,if flag:

, , , , , , , ,flag = False

, , , , , , , ,list.append('------------')

, , , , , ,OldFile = it[0]

, , , , , ,OldPath = it[1]

# -----------------

# Main:

Mpath = os.getcwd()

GetListFiles(Mpath)

CompareList()

if len(list) == 0:

, ,print('Дубликатов нет.')

else:

, ,new_file = open(fn2,'w')

, ,for i in list: #

, , , ,new_file.write(i)

, , , ,print i

, ,print 'Done!'

, ,new_file.close

scan7i.py

#!/usr/bin/env python

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

import sys, os

import zipfile

import datetime

import xml.dom.minidom

# 7 avg 2021

# Запись списка книг в "небазу" (третья,2 версия)

#--------------------------------------------------

Books = []

Errror = []

siz = 0 # размер файла

countFiles = 0

book_title = ''

stroka = ''

replace_val = [('\\', '_'),('/', '_'),(':', '_'),('*', '_'),('?', '_'),('"', '_'),('<', '_'), ('>', '_'), ('|', '_')]

#--------------------------------------------------

def SaveList(fn, L, cco):

, ,if cco > 0:

, , , ,f = open(fn, 'w')

, , , ,for i in L:

, , , , , ,f.write(i)

, , , ,f.close()

def SaveError(fn, L):

, ,if len(L) > 0:

, , , ,f = open(fn, 'w')

, , , ,for i in L:

, , , , , ,f.write(str(i)+'\n')

, , , ,f.close()

#--------------------------------------------------

#**********************************************************************

def parse_fb2(fn):

, ,global Books

, ,global stroka

, ,global book_title

, , , ,

, ,if isinstance(fn, str):

, , , ,fn = open(fn)

, ,try:

, , , ,dom = xml.dom.minidom.parse(fn)

, , , ,

, ,except:

, , , ,print('Error in fb2:')

, , , ,Errror.append(fn)

, , , ,return False

, ,else:

, , , ,dom.normalize()

, , , ,node1=dom.getElementsByTagName("description")[0]

, , , ,titl=node1.getElementsByTagName("title-info")[0]

##

, , , ,book=titl.getElementsByTagName("book-title")[0]

, , , ,book_title = book.childNodes[0].nodeValue

, , , ,book_title = book_title.replace('|', '!')

, , , ,s = book_title +'|'

, , , ,

, , , ,au = ''

, , , ,try:

, , , , , ,for auto in titl.getElementsByTagName("author"):

, , , , , , , ,no1=auto.getElementsByTagName("last-name")[0]

, , , , , , , ,au = au + no1.childNodes[0].nodeValue

, , , , , , , ,no1=auto.getElementsByTagName("first-name")[0]

, , , , , , , ,fi = no1.childNodes[0].nodeValue

, , , , , , , ,au = au + '.'+ fi[0]+'^' , , , , , ,

, , , , , ,au = au[:-1]

, , , ,except:

, , , , , ,au = "NoName."

, , , ,s = s+au

, , , ,stroka = s +'|0|'

, , , ,return True

#**********************************************************************

#--------------------------------------------

def parse_zip(adr):

, ,z = zipfile.ZipFile(adr, 'r')

, ,filelist = z.namelist()

, ,filelist.sort()

, ,for n in filelist:

, , , , try:

, , , , , ,if n[-4:] == ".fb2":

, , , , , , , ,return parse_fb2(z.open(n))

, , , , except:

, , , , , ,print( "Errror:", n )

, , , , , ,return False

#--------------------------------------------------

def replace(line, old_new_num):

, ,for vals in old_new_num:

, , , , , ,# распаковываем кортеж

, , , , , ,old, new = vals

, , , , , ,line = line.replace(old, new)

, ,return line

def my_rename(adr,ph, ex):

, ,co = 0

, ,book_ti = book_title[:20]

# \ / : * ? " <> |

, ,book_ti = replace(book_ti, replace_val)

, ,

, ,a = '-' + book_ti + ex

, ,while os.path.isfile(os.path.join(ph, a)):

, , , ,co += 1

, , , ,a = '-' + book_ti +str(co)+ ex

# , ,print(a)

, ,os.rename(adr,os.path.join(ph, a))

, ,if ex == '.fb2':

, , , ,ex = 'f'

, ,else:

, , , ,ex = 'z'

, ,if co > 0:

, , , ,ex = str(co)+ex

, ,

, ,Books.append(stroka +ex+ '|'+str(siz)+'\n')

, ,

def parse_file(adr,ph):

, ,global siz # размер файла

, ,global countFiles

, ,flag = os.path.basename(adr)[0] != '-'

, ,siz = os.path.getsize(adr)

, ,m = adr.split(".")

, ,if (m[-1] == "zip") and (m[-2] == "fb2"):

, , , ,if flag and parse_zip(adr):

, , , , , , countFiles += 1

, , , , , , my_rename(adr,ph,'.fb2.zip')

, ,elif (m[-1] == "fb2"):

, , , ,if flag and parse_fb2(adr):

, , , , , , countFiles += 1

, , , , , , my_rename(adr,ph,'.fb2') , , , , , ,

, , , ,

def parse_dir(ph):

, ,dirlist = os.listdir(ph)

, ,dirlist.sort()

, ,for i in dirlist:

, , , ,adr = os.path.join(ph, i)

, , , ,if os.path.isdir(adr):

, , , , , ,parse_dir(adr)

, , , ,else:

#? , , , , , ,if os.path.getsize(i) > 0:

, , , , , , , ,parse_file(adr, ph)

#? , , , ,else:

#? , , , , , ,print("bad zip "+ i)

#----------------------------------------

path = os.getcwd()

, ,

#----------------------------------------

if os.path.isfile('NeBaza.txt'):

, ,f = open('NeBaza.txt','r')

, ,for i in f:

, , , , , ,Books.append(i)

, ,f.close()

parse_dir(path)

Books.sort()

SaveList('NeBaza.txt', Books, countFiles )

SaveError('Errror.txt', Errror)#

print( 'Done!')

print( 'Add '+ str(countFiles)+' files.')

12