
以下25个超级实用的Python自动化办公代码,涵盖文件管理、数据处理、文档操作等场景,结合了os、shutil、glob、pandas等模块的高效用法,帮助您轻松实现办公自动化,提升工作效率。
1、批量重命名文件 统一整理文件命名格式,支持递归子目录:
import os
folder_path = "./documents"
for i, filename in enumerate(os.listdir(folder_path)):
new_name = f"report_{i+1}.docx"
os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_nme))2、自动备份文件夹 增量备份重要数据到日期命名的目录:
import shutil
from datetime import date
today = date.today().strftime("%Y%m%d")
shutil.copytree("工作文件", f"备份/{today}_备份")3、递归删除空文件夹 清理无效目录结构:
import os
def remove_empty_dirs(path):
for root, dirs, _ in os.walk(path, topdown=False):
for dir in dirs:
dir_path = os.path.join(root, dir)
if not os.listdir(dir_path):
os.rmdir(dir_path)4、查找重复文件并删除 通过哈希值对比识别重复文件:
import hashlib
def get_file_hash(file_path):
with open(file_path, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
file_hashes = {}
for file in glob.glob("**/*", recursive=True):
file_hash = get_file_hash(file)
if file_hash in file_hashes:
os.remove(file)
else:
file_hashes[file_hash] = file5、合并多个Excel文件 使用pandas快速合并部门报表:
import pandas as pd
files = [f for f in os.listdir() if f.endswith('.xlsx')]
merged = pd.concat([pd.read_excel(f) for f in files], ignore_index=True)
merged.to_excel("总销售报表.xlsx", index=False)6、批量修改Excel数据 标记任务状态(如“待处理”→“已完成”):
from openpyxl import load_workbook
def process_excel(file_path):
wb = load_workbook(file_path)
ws = wb.active
for row in ws.iter_rows(min_row=2, max_col=2):
if row[1].value == "待处理":
row[1].value = "已完成"
wb.save(f"processed_{file_path}")7、自动生成Excel报表 动态创建考勤表:
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "员工考勤报表"
headers = ['姓名', '出勤天数', '请假次数']
for col_num, header in enumerate(headers, 1):
sheet.cell(row=1, column=col_num).value = header
wb.save('员工考勤报表.xlsx')8、批量替换Word模板内容 自动生成客户合同:
from docx import Document
def generate_contract(name, date):
doc = Document("template.docx")
for p in doc.paragraphs:
p.text = p.text.replace("[客户姓名]", name).replace("[日期]", date)
doc.save(f"contract_{name}.docx")9、PDF转Word文档 格式转换工具:
from pdf2docx import Converter
cv = Converter("合同.pdf")
cv.convert("合同.docx")
cv.close()10、批量调整Word样式 统一字体和行距:
from docx import Document
def adjust_style(file_path):
doc = Document(file_path)
for paragraph in doc.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = 12
paragraph.paragraph_format.line_spacing = 1.5
doc.save(file_path)11、自动发送邮件 定时发送日报附件:
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("今日销售数据见附件")
msg["Subject"] = "每日报表"
msg["From"] = "auto@company.com"
msg["To"] = "manager@company.com"
with smtplib.SMTP("smtp.office365.com", 587) as server:
server.starttls()
server.login("user", "password")
server.send_message(msg)import schedule
import time
def job():
print("执行日报生成")
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)13、文件压缩与解压 批量打包日志文件:
import zipfile
with zipfile.ZipFile('logs.zip', 'w') as zipf:
for file in glob.glob("logs/*.log"):
zipf.write(file)14、图像批量处理 调整图片尺寸并旋转:
from PIL import Image
for img_path in glob.glob("photos/*.jpg"):
img = Image.open(img_path)
img.resize((800, 600)).rotate(90).save(f"processed_{img_path}")15、自动化日志记录 记录脚本运行状态:
import logging
logging.basicConfig(filename='app.log', level=logging.INFO)
logging.info("任务执行完成")16、文本分析(词频统计) 使用NLTK处理文档:
from nltk.tokenize import word_tokenize
text = open("report.txt").read()
tokens = word_tokenize(text.lower())
from collections import Counter
print(Counter(tokens).most_common(10))17、跨平台路径处理 兼容Windows/Linux路径:
import os
config_path = os.path.join(os.path.expanduser("~"), "config", "settings.ini")18、桌面文件整理 按扩展名自动分类:
from pathlib import Path
for file in Path("~/Desktop").glob("*"):
if file.suffix:
target_dir = Path("~/Desktop/sorted") / file.suffix[1:]
target_dir.mkdir(exist_ok=True)
file.rename(target_dir / file.name)import os
for dirpath, dirnames, filenames in os.walk('目标路径'):
print(f'当前文件夹: {dirpath}')
print(f'子文件夹: {dirnames}')
print(f'文件列表: {filenames}')path = '目标路径'
print(os.path.isfile(path)) # 判断是否为文件
print(os.path.isdir(path)) # 判断是否为文件夹full_path = 'C:/文件夹/文件.txt'
print(os.path.basename(full_path)) # 获取文件名
print(os.path.splitext(full_path) # 获取扩展名os.makedirs('路径/子路径', exist_ok=True) # 自动创建多级目录import shutil
for file in os.listdir('源文件夹'):
shutil.move(f'源文件夹/{file}', '目标文件夹')search_str = "关键词"
for file in glob.glob('**/*.txt', recursive=True):
with open(file, 'r') as f:
if search_str in f.read():
print(f"找到关键词在: {file}")25、图像灰度化 对图片灰度处理:
from PIL import Image; Image.open('img.jpg').convert('L').save('gray.jpg') # Pillow库图像处理上述Python自动化办公代码涵盖了日常办公中最常见的需求场景。在实际工作中遇到相关需求时可以直接调用这些代码片段,构建出强大的自动化工作流,将重复性工作交给Python处理,提升工作效率,从而专注于更有价值的工作内容。
“无他,惟手熟尔”!有需要的用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!