Python自动化办公入门指南(二):Python基础语法与实战演练
Python自动化办公入门指南,代码实战,get新技能
目录
前言
在掌握了Python的基本概念后,让我们深入探索Python的基础语法。这些基础知识就像办公自动化的"积木",掌握它们后,你将能够构建各种实用的自动化脚本,开启自动化办公大门的钥匙。本篇将结合办公场景,深入讲解核心语法知识,并辅以可直接复用的代码案例,助你快速上手实战。
一、变量与数据类型:办公数据的容器
1.变量概念
在 Python 中,变量是用来存储数据的容器。你可以将数据分配给一个变量,之后通过该变量名访问或修改数据。Python 是动态类型语言,这意味着你在定义变量时不需要指定数据类型,Python 会根据赋给变量的值自动推断其类型。
总结一下,变量具有以下两个特点
-
变量是一个引用,指向一个存储位置(通常是内存中的某个位置),这个存储位置保存着某种类型的数据
-
你可以通过变量名访问和操作数据,Python 会自动跟踪每个变量的数据类型
2.变量命名规则
Python 对变量命名有一些基本的规则和约定:
规则:
-
字母、数字和下划线:变量名只能包含字母(大小写均可)、数字(0-9)和下划线(_)
-
不能以数字开头:变量名不能以数字开头,但可以包含数字,如var1是合法的,但1var不是
-
大小写敏感:Python 是大小写敏感的,所以myVariable和myvariable被视为两个不同的变量
-
不能使用保留字:不能使用 Python 的保留字(关键字)作为变量名,例如if、else、while等
常见的命名规范:
-
小写字母和下划线:Python官方推荐使用小写字母和下划线即(“蛇形命名法”)来命名变量,例如:user_name,total_price
-
避免使用单个字符的变量名:除非在循环等简单场景,通常避免使用如a、b、c这样的单字符变量名。
-
清晰描述:变量名应能清楚表达变量的意义或用途,例如,total_sum 比x更能传达变量的含义
示范:
# 正确示例
employee_name = "李小明" # 员工姓名
department_code = "HR-2023" # 部门编号
monthly_report_count = 12 # 月度报告数量
# 错误示例
2nd_report = "Q3报告" # 变量名以数字开头
if = 5000 # 变量名使用保留关键字
3.常用数据类型
-
字符串(str):文本数据
-
整数(int):整数值
-
浮点数(float):带小数点的数
-
布尔值(bool):True/False
-
列表(list):有序可变集合
-
元组(tuple):有序不可变集合
-
字典(dict):键值对集合
常用办公数据类型
# 字符串处理文件名
file_path = "D:\月度报表\2023-08.xlsx"
# 列表存储多个数据项
report_titles = ["销售报告", "库存清单", "考勤统计"]
# 字典管理员工信息
employee = {
"工号": "A1001",
"姓名": "王芳",
"部门": "财务部",
"薪资": 12500.50
}
4.数据类型转换
# 字符串转数字
num_str = "123"
num_int = int(num_str)
# 数字转字符串
num = 456
num_str = str(num)
# 浮点数取整
price = 19.99
int_price = int(price) # 结果为19
二、条件判断与循环控制流程:智能决策引擎
1. 条件判断(if语句)
# 基本if语句
age = 20
if age >= 18:
print("已成年")
else:
print("未成年")
# 多条件判断
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
2. 循环结构
# for循环
# 打印1到5的数字
for i in range(1, 6):
print(i)
# while循环
# 计算1到100的和
total = 0
i = 1
while i <= 100:
total += i
i += 1
print(f"1到100的和为:{total}")
3.应用示范
条件判断处理文件类型
file_extension = "docx"
if file_extension == "xlsx":
print("正在处理Excel文件...")
elif file_extension == "docx":
print("正在处理Word文档...")
elif file_extension == "pdf":
print("正在处理PDF文件...")
else:
print("不支持的文件格式!")
循环处理批量文件
# 处理文件夹所有Excel文件
file_list = ["销售数据.xlsx", "库存记录.xlsx", "客户信息.xlsx"]
for file in file_list:
if file.endswith(".xlsx"):
print(f"正在处理:{file}")
# 此处可添加实际处理代码
工资计算器(循环+条件)
base_salary = 5000
performance_list = [12000, 8000, 15000, 6000] # 月度业绩
for index, performance in enumerate(performance_list, 1):
if performance > 10000:
bonus = performance * 0.1
elif performance > 5000:
bonus = performance * 0.05
else:
bonus = 0
total = base_salary + bonus
print(f"员工{index}号工资:{total:.2f}元")
三、函数定义与使用:创建你的办公工具箱
1. 定义函数
# 简单函数
def greet(name):
print(f"你好,{name}!")
# 带返回值的函数
def calculate_tax(salary):
if salary > 5000:
return salary * 0.1
else:
return 0
2. 使用函数
# 调用函数
greet("李四")
# 使用返回值
tax = calculate_tax(8000)
print(f"应缴税款:{tax}元")
3.应用示范
文件重命名函数
def batch_rename(prefix, extension, file_list):
"""
批量重命名文件
:param prefix: 文件名前缀
:param extension: 文件扩展名
:param file_list: 原始文件列表
"""
new_files = []
for i, filename in enumerate(file_list, 1):
new_name = f"{prefix}_{i:03d}.{extension}"
new_files.append(new_name)
print(f"重命名 {filename} -> {new_name}")
return new_files
# 使用示例
original_files = ["data1.xlsx", "report.doc", "info.pdf"]
renamed_files = batch_rename("2023Q3", "xlsx", original_files)
邮件内容生成器
def generate_email(template, receiver, content):
"""
生成标准邮件内容
:param template: 邮件模板
:param receiver: 收件人信息
:param content: 邮件正文内容
"""
email_body = f"""
{template['header']}
尊敬的{receiver['name']}:
{content}
{template['footer']}
发件人:{template['sender']}
"""
return email_body
# 使用示例
template = {
"header": "【重要】月度工作报告通知",
"footer": "请于周五前提交至部门邮箱",
"sender": "行政部"
}
receiver_info = {"name": "张经理", "email": "zhang@company.com"}
print(generate_email(template, receiver_info, "本月工作报告提交截止日期为2023-09-30"))
四、文件读写操作:数据持久化管理
1. 读取文件
# 读取文本文件
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 逐行读取
with open('data.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # 去除换行符
2. 写入文件
# 写入文本文件
data = ["第一行", "第二行", "第三行"]
with open('output.txt', 'w', encoding='utf-8') as f:
for line in data:
f.write(line + '\n')
# 追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("这是追加的内容\n")
3.应用示范
日志记录器
def write_log(log_file, event):
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"[{timestamp}] {event}\n")
# 使用示例
write_log("system.log", "开始处理销售数据")
write_log("system.log", "完成数据清洗操作")
配置文件读取
def read_config(config_file):
settings = {}
with open(config_file, "r", encoding="utf-8") as f:
for line in f:
if "=" in line:
key, value = line.strip().split("=")
settings[key] = value
return settings
# config.ini 示例内容:
# output_path=D:/reports
# max_files=100
# default_format=xlsx
config = read_config("config.ini")
print(f"输出路径:{config['output_path']}")
五、综合案例
1. 员工数据处理
# 员工数据
employees = [
{"name": "张三", "age": 25, "salary": 8000},
{"name": "李四", "age": 30, "salary": 12000},
{"name": "王五", "age": 28, "salary": 9500}
]
# 计算平均工资
total_salary = 0
for emp in employees:
total_salary += emp['salary']
average_salary = total_salary / len(employees)
print(f"平均工资:{average_salary:.2f}元")
# 筛选高薪员工
high_salary_emps = [emp for emp in employees if emp['salary'] > 10000]
print("高薪员工:")
for emp in high_salary_emps:
print(f"{emp['name']}: {emp['salary']}元")
2. 文件内容统计
def count_file_stats(filename):
line_count = 0
word_count = 0
char_count = 0
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
line_count += 1
words = line.split()
word_count += len(words)
char_count += len(line)
return {
'lines': line_count,
'words': word_count,
'chars': char_count
}
# 使用示例
stats = count_file_stats('example.txt')
print(f"行数:{stats['lines']}")
print(f"单词数:{stats['words']}")
print(f"字符数:{stats['chars']}")
3.自动化考勤统计
def process_attendance(file_path):
"""
处理考勤记录文件
:param file_path: 考勤文件路径
:return: 统计结果字典
"""
attendance_data = {}
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("#") or not line.strip():
continue # 跳过注释和空行
parts = line.strip().split(",")
name, date, status = parts[0], parts[1], parts[2]
if name not in attendance_data:
attendance_data[name] = {
"total_days": 0,
"late_count": 0,
"leave_count": 0
}
attendance_data[name]["total_days"] += 1
if status == "late":
attendance_data[name]["late_count"] += 1
elif status == "leave":
attendance_data[name]["leave_count"] += 1
return attendance_data
# 使用示例
result = process_attendance("2023-09-attendance.txt")
for emp, stats in result.items():
print(f"{emp}:")
print(f" 出勤天数:{stats['total_days']}")
print(f" 迟到次数:{stats['late_count']}")
print(f" 请假次数:{stats['leave_count']}")
六、下期预告
在下一篇文章中,我们将深入讲解Excel自动化实战,包括:
-
使用openpyxl操作Excel文件
-
批量生成格式化报表
-
数据自动分析与可视化
-
定时邮件发送周报系统
实践建议:
-
在本地创建practice文件夹进行代码测试
-
尝试修改示例中的参数观察变化
-
将公司实际业务场景抽象为代码逻辑
记住:编程就像学习一门新语言,需要不断练习和实践。建议你尝试修改这些示例代码,创建自己的小项目,在实践中巩固所学知识。
更多推荐

所有评论(0)