Boost Workplace Efficiency with Python Automation Scripts
This article presents practical Python scripts that automate repetitive workplace tasks such as system data entry, Excel file merging and chart creation, Word resume parsing, operational KPI monitoring, and email dispatch, enabling professionals to boost efficiency and focus on higher‑value work.
Many professionals spend countless hours on repetitive tasks that add little value. This article shows how Python can automate such work, offering ready-to-use scripts for system entry, Excel processing, Word resume extraction, operational monitoring, and email sending.
System Entry Automation
When you repeatedly input data into a system, a simple script can mimic clicks and fill forms.
import time
from splinter import Browser
def splinter(url):
browser = Browser()
browser.visit(url)
time.sleep(5)
browser.find_by_id('idInput').fill('xxxxxx')
browser.find_by_id('pwdInput').fill('xxxxx')
browser.find_by_id('loginBtn').click()
time.sleep(8)
browser.quit()
if __name__ == '__main__':
websize = 'https://mail.163.com/'
splinter(websize)Similarly, a basic game‑idle script can control the mouse.
import win32api, win32con, time, random
def move_click(x, y, t=0):
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
if t == 0:
time.sleep(random.random()*2+1)
else:
time.sleep(t)
return 0
move_click(30, 30)
def resolution():
return win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)Excel Automation
To merge multiple Excel files into one, use xlrd to read and xlsxwriter to write.
# -*- coding: utf-8 -*-
import xlrd
import xlsxwriter
def getsheet(fh):
return fh.sheets()
def getnrows(fh, sheet):
return fh.sheets()[sheet].nrows
def getFilect(file, shnum):
fh = open_xls(file)
table = fh.sheets()[shnum]
num = table.nrows
for row in range(num):
rdata = table.row_values(row)
datavalue.append(rdata)
return datavalueOr concatenate dataframes directly:
for i in var_list:
df_0 = data[['var_1','var_2','var_3','var_4',i]][data[i]=='信息']
df_0['month'] = date_replace(i)
df_0 = df_0[['var_1','var_2','var_3','var_4','var_5']]
li.append(df_0)
writer = pd.ExcelWriter(r'C:\Users\mapping.xlsx')
df = pd.concat(li)
df.to_excel(writer,'Sheet1',index=False,header=None)Adding charts:
import xlsxwriter
data = [20,45,26,18,45]
workbook = xlsxwriter.Workbook("temp.xlsx")
worksheet = workbook.add_worksheet("data")
worksheet.write_column('A1', data)
chart = workbook.add_chart({'type':'line'})
chart.add_series({
'values':'=data!$A1:$A6',
'name':'Chart Name',
'marker':{'type':'circle','size':8,'border':{'color':'black'},'fill':{'color':'red'}},
'data_labels':{'values':True},
'trendline':{'type':'polynomial','order':2,'name':'Trendline','forward':0.5,'backward':0.5,'display_equation':True,'line':{'color':'red','width':1,'dash_type':'long_dash'}}
})
worksheet.insert_chart('c1', chart)
workbook.close()Word Key‑Info Extraction
For thousands of resumes, extract fields like name, gender, ethnicity using regex on the docx’s XML content.
import re
def get_field_value(text):
value_list = []
m = re.findall(r"姓 名(.*?)性 别", text)
value_list.append(m)
m = re.findall(r"性 别(.*?)学 历", text)
value_list.append(m)
m = re.findall(r"民 族(.*?)健康状况", text)
value_list.append(m)
return value_listAutomated Operation Monitoring
Collect daily KPI data and store results automatically, either from offline files or directly from databases.
from impala.dbapi import connect
from impala.util import as_pandas
import pandas as pd
conn = connect(host='host',port=21050,auth_mechanism='PLAIN',user='user',password='password')
df_data = pd.read_excel('temp.xlsx')
rows = []
for index, row in df_data.iterrows():
rows.append('(' + '"' + str(row['case_id']).replace('nan','null') + '"' + ',' + '"' + str(row['birth_date']) + '"' + '),')
a = '''
INSERT into table
(case_id, birth_date)
values '''
for i in rows:
a += i
a = a[:-1]
cursor1 = conn.cursor()
cursor1.execute(a)
cursor1.close()
conn.close()
print('成功导入数据至数据库...')Running SQL scripts:
import sql
sql_end = sql.sql_end
cursor1 = conn.cursor()
for i in sql_end.split(';'):
cursor1.execute(i)
cursor1.close()
conn.close()
print('程序运行结束,请执行下一步。')Automated Email Sending
Use the email and smtplib modules to compose HTML bodies, embed images, attach files, and send them programmatically.
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
msg = MIMEMultipart()
df_text = '''<html><body><p>Hi all,</p><p>This is a test email, see attachment.</p><p>See the figure below:</p></body></html>'''
msgtext = MIMEText(df_text, 'html', 'utf-8')
msg.attach(msgtext)
image = open('temp.jpg','rb')
msgimage = MIMEImage(image.read())
msg.attach(msgimage)
msgfile = MIMEText(open('temp.xlsx','rb').read(),'base64','utf-8')
msgfile["Content-Disposition"] = 'attachment; filename="temp.xlsx"'
msg.attach(msgfile)
email_host = ''
sender = ''
password = ''
receiver = ''
try:
smtp = smtplib.SMTP(host=email_host)
smtp.connect(email_host)
smtp.starttls()
smtp.login(sender, password)
smtp.sendmail(sender, receiver.split(','), msg.as_string())
smtp.quit()
print('发送成功')
except Exception:
print('发送失败')These examples demonstrate how Python can turn tedious manual work into automated workflows, freeing time for higher‑value activities.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
