注:基于艺赛旗设计器开发
1. 自定义添加日志
import time, os
# file_content:日志内容
def add_logs(file_content):
time_name = time.strftime('%Y%m%d',time.localtime(time.time()))
file_dir = '日志文件存放目录'
file_name = '前缀' + str(time_name)
path = file_dir.strip()
isExists = os.path.exists(path)
if not isExists:
# 如果不存在则创建目录,存在就往文件中写日志
os.makedirs(path)
file_path = open(file_dir + file_name + '.log','a')
file_path.write(file_content)
file_path.close()
2. 自定义记录台账
import ubpa.iexcel as iexcel
import shutil
# path:台账模板文件路径
def makedir_account(path):
t1 = time.strftime('%Y%m%d',time.localtime(time.time()))
path1 = '台账存放目录' + t1
if not os.path.exists(path1):
# 如果不存在则创建
os.makedirs(path1)
iexcel.close_excel_apps()
shutil.copy(path,path1)
account = path1 + '台账文件名'
if os.path.exists(path1):
account = path1 + '台账文件名'
return account
3. excel去除重复行
import pandas as pd
# path1为需去重的excel所在路径,path2为去重后文件内容保存路径
def duplicate(path1,path2):
data = pd.DataFrame(pd.read_excel(path1,'Sheet1'))
print(data)
# 查看是否有重复行
re_row = data.duplicated()
print(re_row)
# 去除重复行
no_re_row = data.drop_duplicates()
print(no_re_row)
# 基于某列去除重复行
wp = data.drop_duplicates(['列名'])
# 将去除重复行后的数据输出到excel中
no_re_row.to_excel(path2)
4. 解压7z压缩包
import os
# path:需解压的压缩包路径
def unzip(path):
folder_name = '7z解压软件所在路径'
# 定位到指定路径
os.chdir(folder_name)
z_path = path
un_path, name = os.path.splitext(z_path)
un_path = '"{}"'.format(un_path)
cmd = '7z.exe x "{}" -o{} -aos -r'.format(z_path,un_path)
os.system(cmd)
5.excel设置访问密码
import win32com.client
"""
excel文件设置访问密码
"""
def set_pwd_xlsx(dec_path, enc_path, pw_str):
"""
param:dec_path:excel文件路径,enc_path:excel保存路径,pw_str:密码字符串
"""
xcl = win32com.client.Dispatch("Excel.Application")
wb = xcl.workbooks.open(dec_path, False, False)
xcl.DisplayAlerts = True
wb.SaveAs(enc_path, None, pw_str)
wb.Close()
xcl.Quit()
6.生成指定目录下文件路径
import os
"""
生成指定目录下所有文件路径
"""
def get_files_path(dir_name):
# dir_name:目录路径
stack = []
result_xlsx = []
stack.append(dir_name)
# 栈空代表所有目录均已遍历
while len(stack) != 0:
temp_name = stack.pop()
try:
temp_name2 = os.listdir(temp_name)
for ex in temp_name2:
stack.append(temp_name + "\\" + ex)
except:
result_xlsx.append(temp_name.strip())
return result_xlsx
7.获取验证码
import re, pytesseract
from PIL import Image
"""
获取验证码
"""
def get_tesseract(img_path, lang=None):
txt = None
try:
image = Image.open(img_path)
txt = pytesseract.image_to_string(image, lang=lang)
if txt:
txt = re.sub('\D', '', txt)
# logger.info(f'ocr识别函数验证码【{txt}】')
except Exception as e:
# logger.error(f'ocr识别函数:{e}')
finally:
return txt