大神论坛

找回密码
快速注册
查看: 107 | 回复: 0

[源码] python源代码汇总 python各种小工具源代码

主题

帖子

0

积分

初入江湖

UID
667
积分
0
精华
威望
0 点
违规
大神币
68 枚
注册时间
2023-10-14 10:49
发表于 2023-12-17 11:05
本帖最后由 a1100330 于 2023-12-17 11:05 编辑

相关模块

# -*-coding:UTF-8 -*-
import tkinter,json,pythoncom
import os,sys,wmi,winsound,win32api
from os import stat,remove
import random,win32print
import gzip,io,win32com
import time,win32com.client
from tkinter.font import Font
from tkinter import ttk
from tkinter.colorchooser import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from ttkthemes import * #add ttkthemes in pycharm #copy ttkthemes-3.2.2 in the projext #cd E:\lab\trans-note21.210\ttkthemes-3.2.2 #python setup.py install
from win32com.client import Dispatch, constants
from win32com.client import DispatchEx
from threading import Thread,Lock
from threading import Timer
from nt import system
from datetime import datetime
from hashlib import md5
import win32com.client as win32
from pathlib import Path # from pathlib import Path
from wxpy import * #import wx # #pip install -U wxPython
# docx files-------------------------------
import pandas as pd
import pypinyin,urllib,csv,docx,sympy,windnd,xlrd,xlsxwriter
from pypinyin import Style
import inspect
import docx #pip install python_docx
import qrcode,binascii,pyAesCrypt,chardet #from tkinter import filedialog
from PIL import Image #add it pillow and pillow-pil in pycharm
import fitz #pip install pymupdf
#from pdf2image import convert_from_path # ## pip install pdf2image # or pip install --user pdf2image
from pdfplumber import open as openpd #import pdfplumber # #add it in pycharm
# pdfminer 在软件里可以不要,但是开发环境需要
import sqlite3 #for mail_log
import matplotlib.pylab as plt
import numpy as np
from spellchecker import SpellChecker
import enchant # from enchant.checker import SpellChecker # pip install pyenchant -i https://pypi.douban.com/simple/
import openpyxl as vb
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from itertools import chain
from pypinyin import pinyin, Style
from xml.dom.minidom import parse
from string import *
from pandas import read_csv
# from pdf2docx import Converter
import xlwings as xw
# net-------------------------------------
import requests
from urllib.parse import urlencode
import requests,mistune,smtplib
import shutil,datetime,hashlib
import http.client
from aip import AipOcr
import webbrowser as web
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import baidu_fanyi_api_zh2en
import baidu_fanyi_api_en2zh
import baidu_fanyi_api_zh2jp
import baidu_fanyi_api_jp2zh
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import wenxin_api
#pip install wenxin_api
# pip install docxcompose
from docxcompose.composer import Composer
import urllib.parse
'''
pip or pip3
#pip install wenxin_api
#pip install --upgrade wenxin_api
#pip install websocket-client==0.57.0
pip3 install requests
pip3 install baidu-aip
pip3 install wxpy
pip3 install line
pip3 install sympy
pip3 install openpyxl
pip3 install xlsxwriter -i https://pypi.douban.com/simple/
pip3 install pdfplumber
pip3 install python-pptx
pip3 install python-docx
pip3 install qrcode
pip3 install pyAesCrypt
python setup.py install用来安装下载的python包
pip3 install mistune -i https://pypi.douban.com/simple/
pip3 install pyspellchecker -i https://pypi.douban.com/simple/
pip3 install pyinstaller -i https://pypi.douban.com/simple/
pip3 install pyenchant -i https://pypi.douban.com/simple/
pip uninstall pillow
pip install pillow -i https://pypi.douban.com/simple/
get pillow 9.5
python.exe -m pip install --upgrade pip
pip3 install windnd 拖放打开的模块
'''

删除选中目录和子目录的重复文件

def killrepeatfiles():
# from win32com.shell import shell, shellcon
from pathlib import Path

# def deltorecyclebin(filename):
# res = shell.SHFileOperation((0, shellcon.FO_DELETE, filename, None,
# shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
# None))
def getmd5(filename):
with open(filename, 'rb') as f:
data = f.read()
file_md5 = hashlib.new("md5", data).hexdigest()
return file_md5

killrepeatwhere = askdirectory() + '/' # 批量翻译文档来源
workwhere2wzsbtp_laodoc=killrepeatwhere
e1workwherewzsbtp_laowendang.delete(0, 'end')
e1workwherewzsbtp_laowendang.insert(0, workwhere2wzsbtp_laodoc)
path=killrepeatwhere
all_size = {}
total_file = 0
total_delete = 0
all_files = Path(path).glob('*.*')
all_files = sorted(all_files, reverse=True)
for file in all_files:
size = file.stat().st_size
name_and_md5 = [file, '']
if size in all_size.keys():
new_md5 = getmd5(file)
if all_size[size][1] == '':
all_size[size][1] = getmd5(all_size[size][0])
if new_md5 in all_size[size]:
try:
file.unlink()
# deltorecyclebin(file)
except:
pass
total_delete += 1

else:
all_size[size].append(new_md5)
else:
all_size[size] = name_and_md5
total_file += 1
# print(f'删除当前目录重复文件')
time.sleep(0.1)
# showinfo('提示', f' 删除目录{path} 的重复文件. \n 文件总数:{total_file} \n 删除个数:{total_delete}')
runingpb() # kill sub folders-----------------------
allfile3 = []
def getallfile(path2):
allfilelist = os.listdir(path2)
for file in allfilelist:
filepath = os.path.join(path2, file) # 判断是不是文件夹
if os.path.isdir(filepath):
getallfile(filepath) # add sub folder's files
allfile3.append(filepath) # path = folderlistpath3
path2 = killrepeatwhere
getallfile(path2) # path = r"C:\Users\guest05\Desktop\cc"
for item3 in allfile3:
all_size = {}
total_file = 0
total_delete = 0
all_files = Path(item3).glob('*.*')
all_files = sorted(all_files, reverse=True)
for file in all_files:
size = file.stat().st_size
name_and_md5 = [file, '']
if size in all_size.keys():
new_md5 = getmd5(file)
if all_size[size][1] == '':
all_size[size][1] = getmd5(all_size[size][0])
if new_md5 in all_size[size]:
try:
file.unlink()
# deltorecyclebin(item3)
except:
pass
total_delete += 1
else:
all_size[size].append(new_md5)
else:
all_size[size] = name_and_md5
total_file += 1
# print(f'删除当前目录重复文件-子目录')
print(f'文件总数:{total_file}')
print(f'删除个数:{total_delete}')
time.sleep(0.1)
runingpb()
showinfo('提示', '目录和子目录重复内容清理完毕.')

txt -> xlsx

from openpyxl import Workbook
from tkinter import ttk
import csv
from tkinter.colorchooser import *
from tkinter.filedialog import *
from tkinter.messagebox import *
def txt2xlsxrd():
ret=askquestion('提示', '列和列之间用tab分割(或 空格),格式对了么?即将导出为xlsx表格,请选择保存位置。')
if ret=='no':
print('no')
if ret=='yes':
print('start')
txt2xlsx()
runingpb()
def txt2xlsx():
neirongxlsx = textPad.get(1.0, END)
fcsv=open("tocsv.txt", "w").write(neirongxlsx)
#fcsv.close()
csvFile2 = open("tmp.csv", 'w', newline='', encoding='GB2312')
writer = csv.writer(csvFile2)
csvRow = []
f = open("tocsv.txt", 'r', encoding='GB2312')
for line in f:
csvRow = line.split()
writer.writerow(csvRow)
f.close()
csvFile2.close()
# --csv to xlsx
from openpyxl import Workbook
data_initial = open("tmp.csv", "r")
sys.getdefaultencoding()
workbook = Workbook()
worksheet = workbook.worksheets[0]
with data_initial as f:
data = csv.reader((line.replace('\0', '') for line in data_initial), delimiter=",")
for r, row in enumerate(data):
for c, col in enumerate(row):
for idx, val in enumerate(col.split('/')):
cell = worksheet.cell(row=r + 1, column=c + 1)
cell.value = val
outfilename = asksaveasfilename(initialfile='未命名.xlsx', defaultextension='.xlsx')
workbook.save(outfilename)

调用 主流浏览器 谷歌 or edge打开网页版微信

def play2():  #web 微信
# import webbrowser
# play_url='https://wx.qq.com/'
# #http://fy.iciba.com/
# webbrowser.open(play_url)
if os.path.exists('C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'):
import webbrowser as web
#url = 'https://note.youdao.com/web'
url='https://wx.qq.com/'
browser_path = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
web.register('Microsoft Edge', None, web.BackgroundBrowser(browser_path))
web.get('Microsoft Edge').open_new_tab(url)
elif os.path.exists('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'):
import webbrowser as web
#url = 'https://note.youdao.com/web'
url='https://wx.qq.com/'
browser_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
web.register('chrome', None, web.BackgroundBrowser(browser_path))
web.get('chrome').open_new_tab(url)


else:
os.startfile("wxweb.exe")
while not os.path.exists('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'):
time.sleep(3)
import webbrowser as web
#url = 'https://note.youdao.com/'
url='https://wx.qq.com/'

browser_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
web.register('chrome', None, web.BackgroundBrowser(browser_path))
web.get('chrome').open_new_tab(url)

epub转txt

# from urllib.request import urlopen


#pip install EbookLib


from nt import chdir


#pip install beautifulsoup4


pip install lxml


import ebooklib

#add ebooklib-re in pycharm

from ebooklib import epub

def readepub():
# from urllib.request import urlopen #pip install EbookLib
from bs4 import BeautifulSoup
# from nt import chdir #pip install beautifulsoup4 pip install lxml
showinfo('notice', '准备选一个epub文件,然后选择保存txt位置,接着耐心等待直到提示完成,过程中有进度条反复走动.')
bookpath=askopenfilename(title='选一个epub文件', defaultextension='.epub')
outfilenameepub2txt = asksaveasfilename(title='选择保存txt位置', initialfile='未命名.txt', defaultextension='.txt')
import ebooklib #add ebooklib-re in pycharm
from ebooklib import epub
book = epub.read_epub(bookpath)
i=0 # outfilename = asksaveasfilename(title='选择保存note位置', initialfile='未命名.note', defaultextension='.note')
for doc in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
# print (doc)
for doc in book.get_items():
# 提取书中的文本内容
if doc.get_type() == ebooklib.ITEM_DOCUMENT: # epub中的内容是html格式,使用BeautifulSoup可以完美解析
soup = BeautifulSoup(doc.get_content(), 'html') # print(soup.text) # textPad.insert(1.0, soup.text)

with open(outfilenameepub2txt, 'a', encoding='utf-8') as fileepub2txt:
fileepub2txt.write(soup.text)
runingpb()
break

showinfo('notice','输出txt完成')

利用正则的字符串的头尾查找

import re


def superfind():
aa=entryvar.get()
zz=entryvar2.get()
print(aa)
print(zz)
super= re.findall(r"%s(.+?)%s"%(aa,zz), textPad.get(1.0, END))
print('super=', super)
for i in super:
print(i)
super2 = str(i)
print('super2=', super2)
textPad.tag_config(super2,foreground='red')
#sn4= abbcc', 'avvff
def search(text_widget, keyword, tag):
pos = '1.0'
while True:
idx = text_widget.search(keyword, pos, END)
if not idx:
break
pos = '{}+{}c'.format(idx, len(keyword))
text_widget.tag_add(tag, idx, pos)
search(textPad, super2,super2)# A Z search start

glabel = ttk.Label(toolbar, text='A*Z:')
glabel.pack(side=LEFT,pady=2)
entryvar = StringVar()
gentry = ttk.Entry(toolbar, textvariable=entryvar,width=13)
gentry.pack(side=LEFT,pady=2)
gentry.insert(0,'关键词A')
entryvar2 = StringVar()
gentry = ttk.Entry(toolbar, textvariable=entryvar2,width=13)
gentry.pack(side=LEFT,pady=2)
gentry.insert(0,'关键词Z')
gbutton = ttk.Button(toolbar, command=superfind, text='查找',width=4)
gbutton.pack(side=LEFT,pady=2)

表格变成文本后的转置

#pip install line
import fileinput
def biaozhuanzhi_xlsx():
import pandas as pd
neirongxlsx2 = textPad.get(1.0, END)
fcsv=open("tocsv2.txt", "w").write(neirongxlsx2)
#fcsv.close()
csvFile2 = open("tmp2.csv", 'w', newline='', encoding='GB2312')
writer = csv.writer(csvFile2)
csvRow = []
f = open("tocsv2.txt", 'r', encoding='GB2312')
for line in f:
csvRow = line.split()
writer.writerow(csvRow)
f.close()
csvFile2.close()
# --csv to xlsx
from openpyxl import Workbook
data_initial = open("tmp2.csv", "r")
sys.getdefaultencoding()
workbook = Workbook()
worksheet = workbook.worksheets[0]
with data_initial as f:
data = csv.reader((line.replace('\0', '') for line in data_initial), delimiter=",")
for r, row in enumerate(data):
for c, col in enumerate(row):
for idx, val in enumerate(col.split('/')):
cell = worksheet.cell(row=r + 1, column=c + 1)
cell.value = val
#outfilename = asksaveasfilename(initialfile='未命名.xlsx', defaultextension='.xlsx')
workbook.save('tmpxlsx2zhuan.xlsx')

df = pd.read_excel('tmpxlsx2zhuan.xlsx')
# 读取需要转置的文件
df = df.T
# 转置
df.to_excel('tmpxlsx2zhuanhou.xlsx')
# 另存为xlsx文件
textPad.delete("1.0", 'end')
# global addxlsxfile
#addxlsxfile = askopenfilename(defaultextension='.xlsx')
wb = load_workbook('tmpxlsx2zhuanhou.xlsx')
# 获取workbook中所有的表格
sheets = wb.sheetnames
print(sheets)
# 循环遍历所有sheet
for i in range(len(sheets)):
sheet = wb[sheets]
print('\n\n第' + str(i + 1) + '个工作表: ' + sheet.title + '->>>\n')
#textPad.insert('end', '\n\n第' + str(i + 1) + '个工作表: ' + sheet.title + '->>>\n')
for r in range(1, sheet.max_row + 1):
if r == 1:
partt01 = ''.join(
[str(sheet.cell(row=r, column=c).value).ljust(17) for c in range(1, sheet.max_column + 1)]).replace(
'None', '*')

print(''.join(
[str(sheet.cell(row=r, column=c).value).ljust(17) for c in range(1, sheet.max_column + 1)]))

textPad.insert('end', partt01.replace('Unnamed:', '').replace('* 0 ', '0 '))
textPad.insert('end', '\n')
else:
partt02 = ''.join(
[str(sheet.cell(row=r, column=c).value).ljust(17) for c in range(1, sheet.max_column + 1)]).replace(
'None', '*')
print(
''.join([str(sheet.cell(row=r, column=c).value).ljust(17) for c in range(1, sheet.max_column + 1)]))
textPad.insert('end', partt02.replace('Unnamed:', '').replace('* 0 ', '0 '))
textPad.insert('end', '\n')
old01=textPad.get(1.0, 'end')
open("zhengli01.txt", "w").write(old01)
#删除第一行垃圾
import fileinput
#pip install line
for line in fileinput.input("zhengli01.txt", inplace=1):
if not fileinput.isfirstline():
print(line.replace('\n', ''))
with open("zhengli01.txt", "r") as zhenl01:
zzzhenl=zhenl01.read()
textPad.delete(1.0, END)
textPad.insert(1.0, zzzhenl)
runingpb()

比较两份文本列表的差异

import difflib
def mychayi():
from itertools import chain
from pypinyin import pinyin, Style
showinfo('提示','在微信区(old) 和 翻译区(new) 分别 输入列表,每行一个词汇元素,对比增删元素差异会输出到 文本编辑区,然后文件菜单里 导出xlsx表。')
# import difflib
#part1
text1 = textPad5wxhuifu.get("1.0", 'end')
contentOfpaixu1 = list(text1.split('\n'))
def to_pinyin(s):
return ''.join(chain.from_iterable(pinyin(s, style=Style.TONE3)))
textPad5wxhuifu.delete("1.0", 'end')
for word in sorted(contentOfpaixu1, key=to_pinyin):
print(word)
textPad5wxhuifu.insert('end', '\n' + word)
text1_new=textPad5wxhuifu.get("1.0", 'end').replace('\n\n','')
textPad5wxhuifu.delete("1.0", 'end')
textPad5wxhuifu.insert('end',text1_new)
#part2
text2 = textPad3fanyi.get("1.0", 'end')
contentOfpaixu2 = list(text2.split('\n'))
def to_pinyin(s):
return ''.join(chain.from_iterable(pinyin(s, style=Style.TONE3)))
textPad3fanyi.delete("1.0", 'end')
for word in sorted(contentOfpaixu2, key=to_pinyin):
print(word)
textPad3fanyi.insert('end', '\n' + word)
text2_new=textPad3fanyi.get("1.0", 'end').replace('\n\n','')
textPad3fanyi.delete("1.0", 'end')
textPad3fanyi.insert('end', text2_new)
# duibi
text1_lines = text1_new.splitlines()
text2_lines = text2_new.splitlines()
d = difflib.Differ()
diff = d.compare(text1_lines, text2_lines)

# print("\n".join(list(diff)))
# mychayistr="\n".join(list(diff))
# print(type(mychayistr))
textPad.delete("1.0", 'end')
textPad.insert('end', "\n".join(list(diff)))

文本转二维码

#qr-code
import qrcode
from PIL import Image
#生成二维码图片
def make_qr(str,save):
qr=qrcode.QRCode(
version=4,
#生成二维码尺寸的大小 1-40 1:21*21(21+(n-1)*4)
error_correction=qrcode.constants.ERROR_CORRECT_M,
#L:7% M:15% Q:25% H:30%
box_size=10,
#每个格子的像素大小
border=2,
#边框的格子宽度大小
)
qr.add_data(str)
qr.make(fit=True)
img=qr.make_image()
img.save(save)

#生成带logo的二维码图片
def make_logo_qr(str,logo,save):
#参数配置
qr=qrcode.QRCode(
version=4,
error_correction=qrcode.constants.ERROR_CORRECT_Q,
box_size=8,
border=2
)
#添加转换内容
qr.add_data(str)
qr.make(fit=True)
#生成二维码
img=qr.make_image()
img=img.convert("RGBA")
#添加logo
if logo and os.path.exists(logo):
icon=Image.open(logo)
#获取二维码图片的大小
img_w,img_h=img.size
factor=4
size_w=int(img_w/factor)
size_h=int(img_h/factor)
#logo图片的大小不能超过二维码图片的1/4
icon_w,icon_h=icon.size
if icon_w>size_w:
icon_w=size_w
if icon_h>size_h:
icon_h=size_h
icon=icon.resize((icon_w,icon_h),Image.ANTIALIAS)
#详见:http://pillow.readthedocs.org/handbook/tutorial.html
#计算logo在二维码图中的位置
w=int((img_w-icon_w)/2)
h=int((img_h-icon_h)/2)
icon=icon.convert("RGBA")
img.paste(icon,(w,h),icon)
#详见:http://pillow.readthedocs.org/re ... L.Image.Image.paste
#保存处理后图片
img.save(save)
def qrout():
qrneirong = textPad.get(1.0, 'end')
open("qrnote.txt", "wt").write(qrneirong)
outfilenamepng = asksaveasfilename(title='保存二维码',initialfile='未命名qrcode.png', defaultextension='.png')
save_path =outfilenamepng
# 生成后的保存文件
logo = 'logo.jpg'
# logo图片
print('把文字区内容生成二维码,如果程序同目录放一个logo.jpg,则二维码更美观。')
time.sleep(1)
path = os.getcwd() + r'\qrnote.txt'
print(path)
f = open(path, 'rt', encoding='UTF-8')
str = qrneirong = textPad.get(1.0, 'end')
# make_qr(str)
str2=str.replace('\t', '\n ')
make_logo_qr(str2, logo, save_path)
runingpb()
os.startfile( outfilenamepng)
#qr-code-end------------------

pdf -> jpg or png

import fitz

def pdftoimgha():
showinfo('提示', '万一PDF多页,一些 PNG 图片文件会产生在PDF文件同目录,推荐建立空文件夹后把PDF文件放入.开始选择PDF->') # png
pdfPath =askopenfilename(defaultextension='.pdf')
doc = fitz.open(pdfPath)
pdf_name = os.path.splitext(pdfPath)[0]
for pg in range(doc.pageCount):
page = doc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
zoom_x = 2.0
zoom_y = 2.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG('%s-%s.png'%(pdf_name,pg))

im = Image.open('%s-%s.png' % (pdf_name, pg))
im.save('%s-%s.jpg' % (pdf_name, pg))
os.remove('%s-%s.jpg' % (pdf_name, pg))
showinfo('提示', '文件产生完毕')
def pdftoimgha2jpg():
showinfo('提示', '万一PDF多页,一些 JPG 图片文件会产生在PDF文件同目录,推荐建立空文件夹后把PDF文件放入.开始选择PDF->') #jpg
pdfPath =askopenfilename(defaultextension='.pdf')
doc = fitz.open(pdfPath)
pdf_name = os.path.splitext(pdfPath)[0]
for pg in range(doc.pageCount):
page = doc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
zoom_x = 2.0
zoom_y = 2.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG('%s-%s.png'%(pdf_name,pg))

im = Image.open('%s-%s.png' % (pdf_name, pg))
im.save('%s-%s.jpg' % (pdf_name, pg))
os.remove('%s-%s.png'%(pdf_name,pg))

批量文件夹 解压

import shutil
import zipfile
def plwjjjieya():

showinfo('提示', '去选择一个文件夹,把它里边的zip压缩包各自解压..')
parent_path = askdirectory() + '/'
# 文件类型选择
# 可以自行更改压缩文件类型,需要引入其它工具包,如tarfile等
# 这里是因为在自己的windows上,zip比较常见,其他类型请自行更改
file_flag = '.zip' # 修改需解压的格式 例如:.rar

# 删除已解压的zip文件
# 不建议初次使用,在确定程序无误后可以添加使用
def del_old_zip(file_path):
os.remove(file_path)
# 解压

def decompress(file_path, root):
# 开始
# zipfile打开zip文件
z = zipfile.ZipFile(f'{file_path}', 'r')
# 解压
z.extractall(path=f"{root}")
# path为解压路径,解包后位于该路径下
# 判断是否需要重复解包
for names in z.namelist():
if names.endswith(file_flag):
z.close()
return 1
# 结束
z.close()
return 0

# 因为我在使用过程中发现有些zip解包后会混在一起
# 在平时大家手动解压时可能也会遇到提示是否覆盖的问题
# 下面的两个函数解决这一问题
# 开始要先创建一个大文件夹 与压缩包名字相同
# 避免后期混乱和麻烦
def start_dir_make(root, dirname):
os.chdir(root)
os.mkdir(dirname)
return os.path.join(root, dirname)
# 去除多余文件夹

def rem_dir_extra(root, father_dir_name):
# 递归要注意信息的正常处理 搞不好上一个调用已经改变了东西 而下面的调用还是使用之前的数据
try:
# 判断文件夹重名 开始
for item in os.listdir(os.path.join(root, father_dir_name)):
# 第一步判断是不是一个文件夹,如果不是则跳过本次循环
if not os.path.isdir(os.path.join(root, father_dir_name, item)):
continue
# 判断是否要脱掉一层目录结构
# 文件夹名字要相同,且子目录中只有单独的一个文件夹
if item == father_dir_name and len(
os.listdir(os.path.join(root, father_dir_name))) == 1:
# 改变工作目录
os.chdir(root)
# 将无用文件夹重命名,因为直接移动会有重名错误
os.rename(father_dir_name, father_dir_name + '-old')
# 移动文件后删除空文件夹
shutil.move(os.path.join(root, father_dir_name + '-old', item), os.path.join(root))
os.rmdir(os.path.join(root, father_dir_name + '-old'))
# 将去掉一层目录结构后的文件夹继续作为父本递归处理下去
# 这里要注意,上面已经发生过数据的改动,所以下面递归传参一定要正确!
rem_dir_extra(root, item)
else:
# 处理那些不满足上面条件的文件夹
rem_dir_extra(os.path.join(root, father_dir_name), item)
except Exception as e:
# 打印错误信息
print("清除文件夹出错" + str(e)) # 入口
flag = 1
while flag:
# 循环遍历文件夹
for root, dirs, files in os.walk(parent_path):
# 读取文件名
for name in files:
if name.endswith(file_flag):
# 创建文件夹
new_ws = start_dir_make(root, name.replace(file_flag, ''))
# zip文件地址
zip_path = os.path.join(root, name)
# 解压
flag = decompress(zip_path, new_ws)
# 删除解压后的文件
# 但不删除又可能会重复运行
# 一定要备份或先测试,不然可能会凉,自己选择修改
del_old_zip(zip_path) # 去掉多余的文件结构
rem_dir_extra(root, name.replace(file_flag, ''))
print(f'{root}\\{name}'.join(['文件:', '\n解压完成\n']))
# 由于解压可能解了好几次 所以可能会有已经解压好的父级目录重名无法处理 这里要再处理一次
rem_dir_extra(os.path.split(parent_path)[0], os.path.split(parent_path)[1])
print("解压完成啦,记得检查有没有zip格式之外的呀!\n\n其他格式需要自己改一下了")
showinfo('提示', '批量解压缩任务完成.')

批量文件夹压缩

import zipfile
def plwjjyasuo():

showinfo('提示', '去选择一个文件夹,把它里边的子文件夹各自都产生独立压缩包.')
def zip_yasuo(start_dir):
file_news = start_dir + '.zip'
if not os.path.isfile(file_news):
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
for dir_path, dir_names, file_names in os.walk(start_dir):
file_path = dir_path.replace(start_dir, '')
file_path = file_path and file_path + os.sep or ''
for filename in file_names:
z.write(os.path.join(dir_path, filename), file_path + filename)
z.close()

base_path = askdirectory() + '/'
base_path_list = os.listdir(base_path)
for base_path_list_one in base_path_list:
base_path_list_one_dir = os.path.join(base_path, base_path_list_one)
# 子目录
print("准备压缩需要压缩的子目录", base_path_list_one_dir)
if os.path.isdir(base_path_list_one_dir):
zip_yasuo(base_path_list_one_dir)
runingpb()
showinfo('提示', '批量压缩任务完成.')

show pc info

import os,sys,wmi,winsound,win32api
c = wmi.WMI()
def addpcinfo():
global list
list = []
def info():
list.append("电脑硬件信息")
list.append("\n")
for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
print(interface.MACAddress)
macaddr = interface.MACAddress
for plan_planess in interface.IPAddress:
print(plan_planess)
for BIOSs in c.Win32_ComputerSystem():
list.append("**主 机 名: %s" % BIOSs.Caption)
list.append("**用 户 名: %s" % BIOSs.UserName)
list.append("\n")
for BIOS in c.Win32_BIOS():
list.append("**Bios描述: %s" % BIOS.Description)
list.append("**序列号: %s" % BIOS.SerialNumber)
list.append("\n")
for processor in c.Win32_Processor():
list.append("**CPU型号: %s" % processor.Name.strip())
list.append("**CPU内核: %s 个" % processor.NumberOfCores )
list.append("**CPU基准频率: %s GHz" % (processor.MaxClockSpeed / 1000 ))
list.append("\n")
for memmodule in c.Win32_PhysicalMemory():
totalmemsize = int(memmodule.Capacity)
list.append("**内存厂商: %s" % memmodule.Manufacturer.replace('80AD000080AD','海力士').replace('04CB','威刚'))
list.append("**内存型号: %s" % memmodule.PartNumber)
list.append("**内存大小: %.2fGB" % (totalmemsize / 1024 ** 3))
list.append("\n")
try:
list.append("**内存频率: %s MHz" % memmodule.ConfiguredClockSpeed)
list.append("\n")
except :
print('mem output error')
for xk in c.Win32_VideoController():
list.append("**显卡名称: %s" % xk.name)
#list.append("视频适配器的内存: %s MB" % (xk.AdapterRAM / 1024 ** 2))
list.append("\n")
#https://blog.csdn.net/yw1688/article/details/52386859
for snk in c.Win32_SoundDevice():
list.append("**声卡名称: %s" % snk.name)
list.append("\n")
for disk in c.Win32_DiskDrive(InterfaceType="IDE"):
diskSize = int(disk.size)
list.append("**磁盘名称: %s" % disk.Caption)
list.append("\n")
list.append("**磁盘大小: %.2fGB" % (diskSize / 1024 ** 3))
list.append("\n")
list.append("**磁盘序列号: %s" % disk.SerialNumber)
list.append("\n")
list.append("**驱动器类型 : %s" % disk.InterfaceType )
list.append("\n")
for disk in c.Win32_DiskDrive(InterfaceType="SCSI"):
diskSize = int(disk.size)
list.append("**磁盘名称: %s" % disk.Caption)
list.append("\n")
list.append("**磁盘大小: %.2fGB" % (diskSize / 1024 ** 3))
list.append("\n")
list.append("**磁盘序列号: %s" % disk.SerialNumber)
list.append("\n")
list.append("**驱动器类型 : %s" % disk.InterfaceType)
list.append("\n")
for disk in c.Win32_DiskDrive(InterfaceType="HDC"):
diskSize = int(disk.size)
list.append("**磁盘名称: %s" % disk.Caption)
list.append("\n")
list.append("**磁盘大小: %.2fGB" % (diskSize / 1024 ** 3))
list.append("\n")
list.append("**磁盘序列号: %s" % disk.SerialNumber)
list.append("\n")
list.append("**驱动器类型 : %s" % disk.InterfaceType)
list.append("\n")
for disk in c.Win32_DiskDrive(InterfaceType="1394"):
diskSize = int(disk.size)
list.append("**磁盘名称: %s" % disk.Caption)
list.append("\n")
list.append("**磁盘大小: %.2fGB" % (diskSize / 1024 ** 3))
list.append("\n")
list.append("**磁盘序列号: %s " % disk.SerialNumber)
list.append("\n")
list.append("**驱动器类型 : %s" % disk.InterfaceType)
list.append("\n")
for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
list.append(" **当前IP地址: %s" % interface.IPAddress[0])
list.append("**当前MAC地址: %s" % macaddr)
list.append("\n")
info()
#runingpb()
textPad.insert('end', list)
textPad3fanyi.insert('end',textPad.get("1.0", 'end'))
newpcinfo=textPad3fanyi.get("1.0", 'end').replace("} {",'\n').replace('\n\n\n','\n').replace('}\n','').replace('**主 机 名','**主机名').replace('**用 户 名','**用户名').replace(' MHz','MHz').replace(' GHz','GHz').replace('电脑硬件信息 {\n\n','')
#.replace(' ','')
textPad.delete("1.0", 'end')
textPad.insert("1.0", newpcinfo)
textPad3fanyi.delete("1.0", 'end')

利用人脸识别 做锁屏工具

from aip import AipFace
#baidu-aip in pycharm
import os
import requests
#pip install requests pywin32 pyinstaller beautifulsoup4 lxml
import base64
import json
import cv2
#cv2-tools cv2studio in pycharm
#pyinstaller -F renlian2.py
#python -m pip install --upgrade pip
import time
import datetime
APP_ID = '17694229'
API_KEY = '7ZDjWakxDGB1bbmBhFvANL3Z'
SECRET_KEY = 'GV2r2muWwSzfIqxPKwNLadSOdSv3SpU'
global null
null=''
'''
baidu-yun-api mgmt
https://login.bce.baidu.com/?account=&redirect=http%3A%2F%2Fconsole.bce.baidu.com%2Fai%2F%3F_%3D1572830160601%26fromai%3D1#/ai/speech/overview/index
pip
https://www.lfd.uci.edu/~gohlke/pythonlibs/
'''
# 1,准备好申请的人脸识别api,API Key, Secret Key
api1="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=7ZDjWakxDGB1bbmBhFvANL3Z&client_secret=GV2r2muWwSzfIqxPKwNLadSOdSv3SpU"
# api2="https://aip.baidubce.com/rest/2.0/face/v3/match"

# 2,获取token值,拼接API
def get_token():
response=requests.get(api1)
access_token=eval(response.text)['access_token']
api2="https://aip.baidubce.com/rest/2.0/face/v3/match"+"?access_token="+access_token
return api2

# 3,读取图片数据
def read_img(img1,img2):
with open(img1,'rb') as f:
pic1=base64.b64encode(f.read())
with open(img2,'rb') as f:
pic2=base64.b64encode(f.read())
params=json.dumps([
{"image":str(pic1,"utf-8"),"image_type":'BASE64',"face_type":"LIVE"},
{"image":str(pic2,"utf-8"),"image_type":'BASE64',"face_type":"IDCARD"}
])
return params

# 4,发起请求拿到对比结果
def analyse_img(file1,file2):
params=read_img(file1,file2)
api=get_token()
content=requests.post(api,params).text
#print(content)
content2=content+' at '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open("jtlog.txt", "a") as rbfile:
rbfile.write(content2)
rbfile.close()
with open("jtlog2.txt", "wt") as rb2file:
rb2file.write(content2)
rb2file.close()
time.sleep(1)
with open("jtlog2.txt", "rt") as rb3file:
zhuaqu=rb3file.read()+' haha'
if '222013' in zhuaqu:
print('ghost format error')
os.startfile('lock.bat')
if 'pic not has face' in zhuaqu:
print('ghost:pic not has face')
os.startfile('lock.bat')
score=eval(content)['result']['score']
if score>79:
print('相似度为'+str(score)+',是同一人')
time.sleep(5)
else:
print('相似度为'+str(score)+',不是同一人')
os.startfile('lock.bat')


#https://blog.csdn.net/python_pycharm/article/details/80808179


#调用笔记本内置摄像头,所以参数为0,如果有其他的摄像头可以调整参数为1,2

cap=cv2.VideoCapture(0)
sucess,img=cap.read()
k=cv2.waitKey(1)
time.sleep(1)
cv2.imwrite("tmp.jpg",img)
time.sleep(2)
print('loading...')
if k == 27:
#通过esc键退出摄像
cv2.destroyAllWindows()
time.sleep(1)
cap.release()
#close capture
time.sleep(2)
analyse_img("my.jpg","tmp.jpg")

lock.bat内容 :
rundll32.exe user32.dll LockWorkStation

批量制作指定目录所有图片的缩略图

主程序代码
# -*-coding:UTF-8 -*-
# @Time: 2020/9/5
# @Author:luojiabei-rogabet
import win32api
import sys, time, re, os
import tkinter as tk
from tkinter.ttk import *
from tkinter import *
from tkinter import filedialog
disk_list = []
def find_disk():
# 遍历盘符
for i in range(65, 91):
vol = chr(i) + ':/'
if os.path.isdir(vol):
disk_list.append(vol)
print("系统盘符:", disk_list)

def BianLi(rootDir, filename):
inputd()
pattenA = re.compile(u"%s" % filename)
for root, dirs, files in os.walk(rootDir):
for file in files:
# fileSize = os.path.getsize(os.path.join(root,file))
path = os.path.join(root, file)
path = path.replace("\\", "/")
patha=path
match_A = pattenA.search(path)
#ext_name = 'jpg'|'png'|'gif'
#match_B=match_A.endswith(ext_name)
if match_A:
print(patha)
ext_name = 'jpg'
if patha.endswith(ext_name):
print(patha)
import yasuo2
yasuo2.resize_image(patha)
ext_name2 = 'png'
if patha.endswith(ext_name2):
print(patha)
import yasuo2
yasuo2.resize_image(patha)
ext_name3 = 'gif'
if patha.endswith(ext_name3):
print(patha)
import yasuo2
yasuo2.resize_image(patha)

def BianLikb(rootDir, filename):
inputd()
pattenA = re.compile(u"%s" % filename)
for root, dirs, files in os.walk(rootDir):
for file in files:
# fileSize = os.path.getsize(os.path.join(root,file))
path = os.path.join(root, file)
path = path.replace("\\", "/")
patha=path
match_A = pattenA.search(path)
if match_A:
print(patha)
dst_path = patha
ext_name = 'jpg'
if patha.endswith(ext_name):
print(patha)
import yasuo2
yasuo2.resize_image(patha)
ext_name2 = 'png'
if patha.endswith(ext_name2):
print(patha)
import yasuo2
yasuo2.resize_image(patha)
ext_name3 = 'gif'
if patha.endswith(ext_name3):
print(patha)
import yasuo2
yasuo2.resize_image(patha)
def savekuan():
kuan2 = t3.get(0.0, 'end')
kuan = kuan2.replace('\n', '')
with open("kuanjpg.txt", "w") as wantfile:
wantfile.writelines(kuan)
def savesize():
mb2 = t2.get(0.0, 'end')
mb = mb2.replace('\n', '')
with open("sizejpg.txt", "w") as wantfile:
wantfile.writelines(mb)
def inputd():
global filename
filename = t1.get(0.0, 'end')
filename = filename.replace('\n', '')

def runkuan():
inputd()
print(filename)
find_disk()
for i in disk_list:
print("[+]正在搜索%s盘" % i)
BianLi(i, filename)
progress()
print("[+]完成检索!")

def runkb():
inputd()
print(filename)
find_disk()
for i in disk_list:
print("[+]正在搜索%s盘" % i)
BianLikb(i, filename)
progresskb()
print("[+]完成检索!")

root = tk.Tk()
root.title('Rogabet-搜索图片文件->批量产生缩略图(\images里)')
root.geometry('450x180')

l1 = tk.Label(root, text='具体使用-查看使用说明:')
l1.grid()
t1 = tk.Text(root, width=27, height=2)
t1.grid(row=1, column=1)
b1 = tk.Button(root, text="*输入要处理的文件名全名或前缀名:", width=35)
b1.grid(row=1, column=0)

b4=tk.Button(root,text='*压到多少宽度?(如输入790-输入后点我):',width=35,command=savekuan)
b4.grid(row=3,column=0)
t3=tk.Text(root,width=9,height=1,autoseparators=False)
t3.grid(row=3,column=1)

b1=tk.Button(root,text='压到多少KB?(如输入300-输入后点我):',width=35,command=savesize)
b1.grid(row=5,column=0)
t2=tk.Text(root,width=9,height=1,autoseparators=False)
t2.grid(row=5,column=1)

b5 = tk.Button(root, text="搜到的图都产生缩略图( KB)(\images里)", width=35, command=runkb)
b5.grid(row=6, column=0)

b3 = tk.Button(root, text="**搜到的图都产生缩略图( 宽)(\images里)", width=35, command=runkuan)
b3.grid(row=4, column=0)
def progress():
# 填充进度条
fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="green")
x = 500 # 未知变量,可更改
n = 465 / x # 465是矩形填充满的次数
for i in range(x):
n = n + 465 / x
canvas.coords(fill_line, (0, 0, n, 60))
root.update()
time.sleep(0.02) # 控制进度条流动的速度
# 清空进度条
fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="white")
x = 500 # 未知变量,可更改
n = 465 / x # 465是矩形填充满的次数
for t in range(x):
n = n + 465 / x
# 以矩形的长度作为变量值更新
canvas.coords(fill_line, (0, 0, n, 60))
root.update()
time.sleep(0) # 时间为0,即飞速清空进度条
def progresskb():
# 填充进度条
fill_line = canvas2.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="green")
x = 500 # 未知变量,可更改
n = 465 / x # 465是矩形填充满的次数
for i in range(x):
n = n + 465 / x
canvas2.coords(fill_line, (0, 0, n, 60))
root.update()
time.sleep(0.02) # 控制进度条流动的速度
# 清空进度条
fill_line = canvas2.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="white")
x = 500 # 未知变量,可更改
n = 465 / x # 465是矩形填充满的次数
for t in range(x):
n = n + 465 / x
# 以矩形的长度作为变量值更新
canvas2.coords(fill_line, (0, 0, n, 60))
root.update()
time.sleep(0) # 时间为0,即飞速清空进度条
canvas = tk.Canvas(root, width=200, height=23, bg="white")
canvas.grid(row=4, column=1) #kuan
canvas2 = tk.Canvas(root, width=200, height=23, bg="white")
canvas2.grid(row=6, column=1) #kb
root.mainloop()

以下是用来调用的模块 yasuo2.py
from PIL import Image
#from shutil import copyfile
import os,time
def readsize():
with open("sizejpg.txt", "r") as want2file:
mysize=want2file.readline()
global mysize2
mysize2=int(str(mysize))

def readkuan():
with open("kuanjpg.txt", "r") as kuanfile:
mykuan=kuanfile.readline()
global mykuan2
mykuan2=int(str(mykuan))

def get_size(file):
# 获取文件大小:KB
size = os.path.getsize(file)
return size / 1024
def get_outfile(infile, outfile):
if outfile:
return outfile
print("处理:"+infile)
#分隔目录和文件名
pathb, allname = os.path.split(infile)
#分隔盘符和文件名
#drv, left = os.path.splitdrive(spath)
#分隔文件和扩展名
# dir, suffix = os.path.splitext(infile)
frontname, ext = os.path.splitext(allname)
pathc = pathb + '/images/'
#os.makedirs(pathc)

#outfile = '{}{}-out{}'.format(pathc, frontname,ext)

if os.path.exists(pathc):
outfile = '{}{}-out{}'.format(pathc, frontname, ext)
else:
os.makedirs(pathc)
outfile = '{}{}-out{}'.format(pathc, frontname, ext)

return outfile
#压缩文件到指定大小,我期望的是150KB,step和quality可以修改到最合适的数值
def compress_image(infile, outfile='',mb=300, step=10, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
:param mb: 压缩目标,KB
:param step: 每次调整的压缩比率
:param quality: 初始压缩比率
:return: 压缩文件地址,压缩文件大小
"""
o_size = get_size(infile)

readsize()
mb=mysize2
print('mb%s'%mb)
if o_size <= mb:
return infile
outfile = get_outfile(infile, outfile)
while o_size > mb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
return outfile, get_size(outfile)
#修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小
def resize_image(infile, outfile='', x_s=1376):
"""修改图片尺寸
:param infile: 图片源文件
:param outfile: 重设尺寸文件保存地址
:param x_s: 设置的宽度
:return:
"""
readkuan()
x_s = mykuan2
im = Image.open(infile)
x, y = im.size
y_s = int(y * x_s / x)
out = im.resize((x_s, y_s), Image.ANTIALIAS)
outfile = get_outfile(infile, outfile)
out.save(outfile)

#compress_image(r'space.jpg')
#resize_image(r'space.jpg')

批量 压缩图片的工具

import os
from tkinter.ttk import *
from tkinter import *
import tkinter as tk
def savesize():
mb2 = t1.get(0.0, 'end')
mb = mb2.replace('\n', '')
with open("sizejpg.txt", "w") as wantfile:
wantfile.writelines(mb)
def savekuan():
kuan2 = t2.get(0.0, 'end')
kuan = kuan2.replace('\n', '')
with open("kuanjpg.txt", "w") as wantfile:
wantfile.writelines(kuan)
def yasuo300():
dst_path =os.getcwd()
ext_name = 'jpg'
for r, d, files in os.walk( dst_path ):
for file in files:
if file.endswith( ext_name ):
print( file )
import yasuo
yasuo.compress_image(file)
def kuandu():
dst_path =os.getcwd()
ext_name = 'jpg'
for r, d, files in os.walk( dst_path ):
for file in files:
if file.endswith( ext_name ):
print( file )
import yasuo
yasuo.resize_image(file)


root=tk.Tk()
root.title('Bofey图片压缩 -> 按照 宽度 或 KB大小 ->批量压缩')
root.geometry()
l1=tk.Label(root,text='把该工具复制到待压图片文件夹后点开始-批量压缩')
l1.grid(row=1,column=0)

b1=tk.Button(root,text='压到多少KB?(如输入300-输入后点我):',width=35,command=savesize)
b1.grid(row=2,column=0)

t1=tk.Text(root,width=9,height=1,autoseparators=False)
t1.grid(row=2,column=1)

b2=tk.Button(root,text='压到多少宽度?(如输入790-输入后点我):',width=35,command=savekuan)
b2.grid(row=3,column=0)

t2=tk.Text(root,width=9,height=1,autoseparators=False)
t2.grid(row=3,column=1)

b3=tk.Button(root,text="开始(指定KB),新文件名out结尾",width=28,command=yasuo300)
b3.grid(row=2,column=2)
b3=tk.Button(root,text="开始(指定宽度),新文件名out结尾",width=28,command=kuandu)
b3.grid(row=3,column=2)
root.mainloop()

以下是 用来调用的 yasuo.py 模块
from PIL import Image
#from shutil import copyfile
import os,time
def readsize():
with open("sizejpg.txt", "r") as want2file:
mysize=want2file.readline()
global mysize2
mysize2=int(str(mysize))

def readkuan():
with open("kuanjpg.txt", "r") as kuanfile:
mykuan=kuanfile.readline()
global mykuan2
mykuan2=int(str(mykuan))

def get_size(file):
# 获取文件大小:KB
size = os.path.getsize(file)
return size / 1024
def get_outfile(infile, outfile):
if outfile:
return outfile
dir, suffix = os.path.splitext(infile)
path = os.getcwd() + '\\images\\'
#outfile = os.getcwd() + '\\images\\' + '{}-out{}'.format(dir, suffix)
if os.path.exists(path):

outfile = os.getcwd() + '\\images\\' + '{}-out{}'.format(dir, suffix)
else:
os.makedirs(path)
outfile = os.getcwd() + '\\images\\' + '{}-out{}'.format(dir, suffix)
#finally:
#outfile = os.getcwd() + '\\images\\'+'{}-out{}'.format(dir, suffix)


return outfile
#压缩文件到指定大小,我期望的是150KB,step和quality可以修改到最合适的数值
def compress_image(infile, outfile='',mb=300, step=10, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
:param mb: 压缩目标,KB
:param step: 每次调整的压缩比率
:param quality: 初始压缩比率
:return: 压缩文件地址,压缩文件大小
"""
o_size = get_size(infile)

readsize()
mb=mysize2
print('mb%s'%mb)
if o_size <= mb:
return infile
outfile = get_outfile(infile, outfile)
while o_size > mb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
return outfile, get_size(outfile)
#修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小
def resize_image(infile, outfile='', x_s=1376):
"""修改图片尺寸
:param infile: 图片源文件
:param outfile: 重设尺寸文件保存地址
:param x_s: 设置的宽度
:return:
"""
readkuan()
x_s = mykuan2
im = Image.open(infile)
x, y = im.size
y_s = int(y * x_s / x)
out = im.resize((x_s, y_s), Image.ANTIALIAS)
outfile = get_outfile(infile, outfile)
out.save(outfile)


#compress_image(r'space.jpg')
#resize_image(r'space.jpg')

利用sqlite做资产管理

# -*-coding:UTF-8 -*-
import win32api
import sys, time, re, os
import tkinter as tk
from tkinter.ttk import *
from tkinter import *
import sqlite3
import csv, codecs
#author: 罗加贝 2021
def itemdeleted():
index2es = lb.curselection()
if (len(index2es) == 0):
return
if (len(index2es) == 1):

wantdelit=lb.get(index2es)
print(wantdelit[0]) #序列号
wantdelititem=wantdelit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''DELETE from pcmgr where pc_sn = ?'''
values = cursor.execute(sql, ( wantdelititem, ))
conn.commit() #update db
if (len(index2es) > 1):

for index in index2es:
# print(lb.get(index))
mysel_ph = lb.get(index)
print(mysel_ph[0]) # 序列号
wantdelititem_sn = mysel_ph[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''DELETE from pcmgr where pc_sn = ?'''
values = cursor.execute(sql, (wantdelititem_sn,))
conn.commit() # update db

def db2txt():
#sel item to txt
indexs = lb.curselection()
for index in indexs:
#print(lb.get(index))
mysel = lb.get(index)
print(str(mysel))
with open("exportdev.txt", "a") as want2file:
want2file.writelines(
str(mysel).replace("('", '').replace("')", '').replace("',", '').replace("'", '') + '\n')
want2file.close()
# to csv
csvFile2 = open("exportdev.csv", 'w', newline='', encoding='GB2312')
writer = csv.writer(csvFile2)
csvRow = []
f = open("exportdev.txt", 'r', encoding='GB2312')
for line in f:
csvRow = line.split()
writer.writerow(csvRow)
f.close()
csvFile2.close()
runingpb()
def csv2db():
import pandas
conn = sqlite3.connect("gsdevmgr.db")
df = pandas.read_csv('device.csv', encoding="GB2312")
df.to_sql('pcmgr', conn, if_exists='append', index=False)
runingpb()
def createpcmgr():
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''Create table pcmgr(
pc_sn text,
pc_model text,
ip_addr text,
mac_addr text,
user text,
dept text,
in_out_lan text,
port_location text,
use_status text,
getit_time text,
devitstype text,
hostname_tip text)'''
cursor.execute(sql)
cursor.close()
conn.close()
def add_anpc():
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
new_pc_sn=input_pc_sn.get()
new_pc_model=input_pc_model.get()
new_ip_addr=input_ip_addr.get()
new_mac_addr=input_mac_addr.get()
new_user=input_user.get()
new_dept=input_dept.get()
new_in_out_lan=input_in_out_lan.get()
new_port_location=input_port_location.get()
new_use_status=input_use_status.get()
new_getit_time=input_getit_time.get()
new_devitstype=input_devitstype.get()
new_hostname_tip=input_hostname_tip.get()
newlog = (new_pc_sn, new_pc_model, new_ip_addr,new_mac_addr,new_user,new_dept,new_in_out_lan,new_port_location,new_use_status,new_getit_time,new_devitstype,new_hostname_tip)
sql = '''INSERT into pcmgr values(?,?,?,?,?,?,?,?,?,?,?,?)'''
cursor.execute(sql, newlog)
conn.commit()
cursor.close()
conn.close()

def showallpcs():
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr'''
results=cursor.execute(sql)
allpcs=results.fetchall()
for anpc in allpcs:
lb.insert(END, anpc)
#print(type(anpc)) #tuple
cursor.close()
conn.close()
runingpb()
def cleanthem():
lb.delete(0, END)
#数据库模糊搜索
def searchanpc():
search_pc_sn = input_pc_sn.get()
search_pc_model = input_pc_model.get()
search_ip_addr = input_ip_addr.get()
search_mac_addr = input_mac_addr.get()
search_user = input_user.get()
search_dept = input_dept.get()
search_in_out_lan = input_in_out_lan.get()
search_port_location = input_port_location.get()
search_use_status = input_use_status.get()
search_getit_time = input_getit_time.get()
search_devitstype = input_devitstype.get()
search_hostname_tip = input_hostname_tip.get()
if search_ip_addr != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where ip_addr like ?'''
values = cursor.execute(sql, ( '%'+search_ip_addr+'%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
#print(type(itt))#tuple
cursor.close()
conn.close()

if search_pc_sn != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where pc_sn like ?'''
values = cursor.execute(sql, ('%'+search_pc_sn+'%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()
if search_use_status != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where use_status like ?'''
values = cursor.execute(sql, ('%' + search_use_status + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()
if search_getit_time != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where getit_time like ?'''
values = cursor.execute(sql, ('%' + search_getit_time + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()

if search_port_location != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where port_location like ?'''
values = cursor.execute(sql, ('%' + search_port_location + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()

if search_in_out_lan != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where in_out_lan like ?'''
values = cursor.execute(sql, ('%' + search_in_out_lan + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()


if search_dept != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where dept like ?'''
values = cursor.execute(sql, ('%' + search_dept + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()

if search_user != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where user like ?'''
values = cursor.execute(sql, ('%' + search_user + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()
if search_devitstype != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where devitstype like ?'''
values = cursor.execute(sql, ('%' + search_devitstype + '%',))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()

if search_mac_addr != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where mac_addr like ?'''
values = cursor.execute(sql, ( '%' +search_mac_addr+ '%' ,))
for itt in values:
lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()

if search_pc_model!= '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where pc_model like ?'''
values = cursor.execute(sql, ('%'+search_pc_model+'%',))
for itt in values:

lb.insert(END,
itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[
10] + ' ' +
itt[11])
cursor.close()
conn.close()
if search_hostname_tip != '':
lb.delete(0, END)
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''SELECT pc_sn, pc_model, ip_addr,mac_addr,user,dept,in_out_lan,port_location,use_status,getit_time,devitstype,hostname_tip
from pcmgr where hostname_tip like ?'''
values = cursor.execute(sql, ('%' + search_hostname_tip + '%',))
for itt in values:
lb.insert(END, itt[0] + ' ' + itt[1] + ' ' + itt[2] + ' ' + itt[3] + ' ' + itt[4] + ' ' + itt[
5] + ' ' + itt[6] + ' ' + itt[7] + ' ' + itt[8] + ' ' + itt[9] + ' ' + itt[10] + ' ' +
itt[11])
cursor.close()
conn.close()
def readyedit():
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
# print(cutwanteditit[1]) #型号
# print(wanteditit[0]) # 序列号
# print(wanteditit[1]) # 型号

wanteditit = lb.get(index)
print(type(wanteditit))
if type(wanteditit) is tuple:
wanteditititem = wanteditit[0] # 序列号
wanteditititem1 = wanteditit[1] # 型号
wanteditititem2 = wanteditit[2] # ip地址
wanteditititem3 = wanteditit[3] # MAC地址
wanteditititem4 = wanteditit[4] # 使用人
wanteditititem5 = wanteditit[5] # 部门
wanteditititem6 = wanteditit[6] # 电话号码 in_out_lan
wanteditititem7 = wanteditit[7] # 点位 port_location
wanteditititem8 = wanteditit[8] # 状态(在仓库\在用) use_status
wanteditititem9 = wanteditit[9] # 取用日期 getit_time
wanteditititem10 = wanteditit[10] # 设备类型 devitstype
wanteditititem11 = wanteditit[11] # 备注(\用途) hostname_tip
gentry1.delete(0, END)
gentry1.insert(0, wanteditititem)
gentry2.delete(0, END)
gentry2.insert(0, wanteditititem1)
gentry3.delete(0, END)
gentry3.insert(0, wanteditititem2)
gentry4.delete(0, END)
gentry4.insert(0, wanteditititem3)
gentry5.delete(0, END)
gentry5.insert(0, wanteditititem4)
gentry6.delete(0, END)
gentry6.insert(0, wanteditititem5)
gentry7.delete(0, END)
gentry7.insert(0, wanteditititem6)
gentry8.delete(0, END)
gentry8.insert(0, wanteditititem7)
gentry9.delete(0, END)
gentry9.insert(0, wanteditititem8)
gentry10.delete(0, END)
gentry10.insert(0, wanteditititem9)
gentry11.delete(0, END)
gentry11.insert(0, wanteditititem10)
gentry12.delete(0, END)
gentry12.insert(0, wanteditititem11)

if type(wanteditit) is not tuple:
#if lb.size()<666:
cutwanteditit = wanteditit.split(' ')
print(cutwanteditit[0]) # 序列号 切割字符串
gentry1.delete(0, END)
gentry1.insert(0, cutwanteditit[0])
gentry2.delete(0, END)
gentry2.insert(0, cutwanteditit[1])
gentry3.delete(0, END)
gentry3.insert(0, cutwanteditit[2])
gentry4.delete(0, END)
gentry4.insert(0, cutwanteditit[3])
gentry5.delete(0, END)
gentry5.insert(0, cutwanteditit[4])
gentry6.delete(0, END)
gentry6.insert(0, cutwanteditit[5])
gentry7.delete(0, END)
gentry7.insert(0, cutwanteditit[6])
gentry8.delete(0, END)
gentry8.insert(0, cutwanteditit[7])
gentry9.delete(0, END)
gentry9.insert(0, cutwanteditit[8])
gentry10.delete(0, END)
gentry10.insert(0, cutwanteditit[9])
gentry11.delete(0, END)
gentry11.insert(0, cutwanteditit[10])
gentry12.delete(0, END)
gentry12.insert(0, cutwanteditit[11])


def cleanabove():
gentry1.delete(0, END)
gentry2.delete(0, END)
gentry3.delete(0, END)
gentry4.delete(0, END)
gentry5.delete(0, END)
gentry6.delete(0, END)
gentry7.delete(0, END)
gentry8.delete(0, END)
gentry9.delete(0, END)
gentry10.delete(0, END)
gentry11.delete(0, END)
gentry12.delete(0, END)
def howmany_item_sel():
gentry13.delete(0, END)
index = lb.curselection()
howmany_item=len(index)
#global howmany_item
#return howmany_item
gentry13.insert(0,howmany_item)

def updateanpc():
update_pc_sn = input_pc_sn.get()
update_pc_model = input_pc_model.get()
update_ip_addr = input_ip_addr.get()
update_mac_addr = input_mac_addr.get()
update_user = input_user.get()
update_dept = input_dept.get()
update_in_out_lan = input_in_out_lan.get()
update_port_location = input_port_location.get()
update_use_status = input_use_status.get()
update_getit_time = input_getit_time.get()
update_devitstype = input_devitstype.get()
update_hostname_tip = input_hostname_tip.get()
if update_pc_sn is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set pc_sn = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_pc_sn,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_pc_sn, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
if update_use_status is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set use_status = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_use_status,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_use_status, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
if update_getit_time is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set getit_time = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_getit_time,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_getit_time, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_port_location is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set port_location = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_port_location,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_port_location, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_in_out_lan is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set in_out_lan = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_in_out_lan,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_in_out_lan, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_ip_addr is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set ip_addr = ? where pc_sn = ?'''

if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_ip_addr,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_ip_addr, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
if update_dept is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set dept = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_dept,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_dept, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_user is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set user = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_user,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_user, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
if update_devitstype is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)

#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set devitstype = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_devitstype,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_devitstype, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_mac_addr is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set mac_addr = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_mac_addr,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_mac_addr, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db

if update_pc_model is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set pc_model = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_pc_model,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_pc_model, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
if update_hostname_tip is not None:
index = lb.curselection()
if (len(index) == 0):
return
# lb.delete(index)
wanteditit = lb.get(index)
#print(wanteditit[0]) # 序列号

#print(cutwanteditit[0]) # 序列号 切割字符串
wanteditititem = wanteditit[0]
conn = sqlite3.connect("gsdevmgr.db")
cursor = conn.cursor()
sql = '''UPDATE pcmgr set hostname_tip = ? where pc_sn = ?'''
if type(wanteditit) is not tuple:
cutwanteditit = wanteditit.split(' ')
param1=(update_hostname_tip,cutwanteditit[0])
values = cursor.execute(sql, param1)
if type(wanteditit) is tuple:
param = (update_hostname_tip, wanteditititem)
values = cursor.execute(sql,param)
conn.commit() # update db
def runingpb():

for i in range(100):
pb['value']=i+1
root.update()
time.sleep(0.05)
from tkinter import ttk
from ttkthemes import *
#root=tk.Tk()
root = ThemedTk(theme="radiance", toplevel=True, themebg=True)
root.title('Rogabet 电脑\显示器\电话等-库存-资产管理')
root.geometry('1379x690')

#表的操作
b1=ttk.Button(root,text="建设备管理表",width=21,command=createpcmgr)
b1.grid(row=0,column=0)
b2=ttk.Button(root,text="新添填写条目",width=21,command=add_anpc)
b2.grid(row=0,column=1)
b3=ttk.Button(root,text="删除选中条目",width=21,command=itemdeleted)
b3.grid(row=0,column=2)
b4=ttk.Button(root,text="保存修改条目",width=21,command=updateanpc)
b4.grid(row=0,column=3)
b5=ttk.Button(root,text="查看所有条目",width=21,command=showallpcs)
b5.grid(row=0,column=4)
b6=ttk.Button(root,text="查询某个条目",width=21,command=searchanpc)
b6.grid(row=0,column=5)

b7=ttk.Button(root,text="点下方某记录->点本按钮->编辑上方填项->点'保存修改'->修改条目完成",width=71,command=readyedit)
b7.grid(row=5,column=0,columnspan=3)
b8=ttk.Button(root,text="清空下方显示区域",width=37,command=cleanthem)
b8.grid(row=5,column=3,rowspan=2,columnspan=2)
b9=ttk.Button(root,text="清空上方填项",width=21,command=cleanabove)
b9.grid(row=5,column=5)
b10=ttk.Button(root,text="device.csv导入库",width=21,command=csv2db)
b10.grid(row=6,column=5)
b11=ttk.Button(root,text="选择下方多条记录后,点击本按钮导出到exportdev.txt(\csv)",width=71,command=db2txt)
b11.grid(row=6,column=0,columnspan=3)

#信息填写区域
l1=ttk.Label(root,text=' 序列号: ',width=21)
l1.grid(row=1,column=0)
input_pc_sn = StringVar()
gentry1 = Entry(root, textvariable=input_pc_sn, width=21)
gentry1.grid(row=1,column=1)
l2=ttk.Label(root,text=' 型号: ')
l2.grid(row=1,column=2)
input_pc_model = StringVar()
gentry2 = ttk.Entry(root, textvariable=input_pc_model, width=21)
gentry2.grid(row=1,column=3)
l3=ttk.Label(root,text=' IP地址: ')
l3.grid(row=1,column=4)
input_ip_addr = StringVar()
gentry3 = Entry(root, textvariable=input_ip_addr, width=21)
gentry3.grid(row=1,column=5)
l4=ttk.Label(root,text=" MAC地址(用'-'分割):" )
l4.grid(row=2,column=0)
input_mac_addr = StringVar()
gentry4 = ttk.Entry(root, textvariable=input_mac_addr, width=21)
gentry4.grid(row=2,column=1)
l5=ttk.Label(root,text=' 使用人: ')
l5.grid(row=2,column=2)
input_user = StringVar()
gentry5 = ttk.Entry(root, textvariable=input_user, width=21)
gentry5.grid(row=2,column=3)
l6=ttk.Label(root,text=' 部门: ')
l6.grid(row=2,column=4)
input_dept = StringVar()
gentry6 = ttk.Entry(root, textvariable=input_dept, width=21)
gentry6.grid(row=2,column=5)
l7=ttk.Label(root,text=' 用途(办公\内网): ')
l7.grid(row=3,column=0)
input_in_out_lan = StringVar()
gentry7 = ttk.Entry(root, textvariable=input_in_out_lan, width=21)
gentry7.grid(row=3,column=1)
l8=ttk.Label(root,text='网线点位: ')
l8.grid(row=3,column=2)
input_port_location = StringVar()
gentry8 = ttk.Entry(root, textvariable=input_port_location, width=21)
gentry8.grid(row=3,column=3)
l9=ttk.Label(root,text=' 状态(在仓库\在用): ')
l9.grid(row=3,column=4)
input_use_status = StringVar()
gentry9 = Entry(root, textvariable=input_use_status, width=21)
gentry9.grid(row=3,column=5)
l10=ttk.Label(root,text=' 取用日期(2021-8-17): ')
l10.grid(row=4,column=0)
input_getit_time = StringVar()
gentry10 = ttk.Entry(root, textvariable=input_getit_time, width=21)
gentry10.grid(row=4,column=1)
l11=ttk.Label(root,text=' 设备类(IP电话\笔记本\台式机): ')
l11.grid(row=4,column=2)
input_devitstype = StringVar()
gentry11 = ttk.Entry(root, textvariable=input_devitstype, width=21)
gentry11.grid(row=4,column=3)
l12=ttk.Label(root,text=' 主机名\通讯号码: ')
l12.grid(row=4,column=4)
input_hostname_tip = StringVar()
gentry12 = ttk.Entry(root, textvariable=input_hostname_tip, width=21)
gentry12.grid(row=4,column=5)
mylisttitle=" -- 系列号 ------ 型号 ------- ip地址 ---- MAC地址 --- 使用人 部门 - 用途 点位 状态 - 取用日期 - 设备类型 - 主机名\号码 -------------------------------------------- "
l13=ttk.Label(root,text=mylisttitle)
l13.grid(columnspan=6)
#l14=ttk.Label(root,text='计数条目个数: ')
#l14.grid(row=9,column=1)
lb=Listbox(root ,width=170,height=25,selectmode=EXTENDED)
lb.grid(columnspan=6)
b12=ttk.Button(root,text="计数选择条目",width=21,command=howmany_item_sel)
b12.grid(row=9,column=0)
input_howmany_sel = StringVar()
gentry13 = ttk.Entry(root, textvariable=input_howmany_sel, width=15)
gentry13.grid(row=9,column=1)
pb = ttk.Progressbar(root, length = 850, value = 0, mode = "determinate")
pb.grid(row=9,column=2,columnspan=4)
pb['maximum']=100
pb['value'] =0
#root.Show() #用于多次打开窗体
root.mainloop()
#del root #用于多次打开窗体

删当前和子目录重复文件

# -*- encoding: utf-8 -*-import os           # 加载文件管理库
# path = r"C:\Users\guest05\Desktop\cc"
from pathlib import Path
import hashlib
import time
def getmd5(filename):
with open(filename, 'rb') as f:
data = f.read()
file_md5 = hashlib.new("md5", data).hexdigest()
return file_md5
def main():
allfile3 = []
def getallfile(path2):
allfilelist = os.listdir(path2)
for file in allfilelist:
filepath = os.path.join(path2, file) # 判断是不是文件夹
if os.path.isdir(filepath):
getallfile(filepath) # add sub folder's files
allfile3.append(filepath) # path = folderlistpath3
path2 = os.getcwd()
getallfile(path2) # path = r"C:\Users\guest05\Desktop\cc"
for item3 in allfile3:
all_size = {}
total_file = 0
total_delete = 0
all_files = Path(item3).glob('*.*')
all_files = sorted(all_files, reverse=True)
# all_files=allfile3
for file in all_files:
# for file in allfile3:
# if file in allfile3:
size = file.stat().st_size
name_and_md5 = [file, '']
if size in all_size.keys():
new_md5 = getmd5(file)
if all_size[size][1] == '':
all_size[size][1] = getmd5(all_size[size][0])
if new_md5 in all_size[size]:
file.unlink()
total_delete += 1
else:
all_size[size].append(new_md5)
else:
all_size[size] = name_and_md5
total_file += 1
print(f'删除当前目录重复文件-子目录')
print(f'文件总数:{total_file}')
print(f'删除个数:{total_delete}')
time.sleep(3)
# current root delete same files
path = os.getcwd()
all_size = {}
total_file = 0
total_delete = 0
all_files = Path(path).glob('*.*')
all_files = sorted(all_files, reverse=True)
for file in all_files:
size = file.stat().st_size
name_and_md5 = [file, '']
if size in all_size.keys():
new_md5 = getmd5(file)
if all_size[size][1] == '':
all_size[size][1] = getmd5(all_size[size][0])
if new_md5 in all_size[size]:
file.unlink()
total_delete += 1
else:
all_size[size].append(new_md5)
else:
all_size[size] = name_and_md5
total_file += 1
print(f'删除当前目录重复文件')

print(f'文件总数:{total_file}')
print(f'删除个数:{total_delete}')
time.sleep(3)
if __name__ == '__main__':
main()


注:若转载请注明大神论坛来源(本贴地址)与作者信息。

返回顶部