
👉 项目官网:https://www.python-office.com/ 👈

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天教你怎么用 python-office 管理代码——自动备份、整理、统计!
1、代码备份
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import office import shutil from datetime import datetime
def backup_code(): """备份代码文件夹""" today = datetime.now().strftime('%Y%m%d_%H%M%S') src = 'C:\\代码\\我的项目' dst = f'D:\\备份\\项目备份_{today}' shutil.copytree(src, dst) print(f'代码已备份到: {dst}')
backup_code()
|
2、统计代码行数
1 2 3 4 5 6 7 8 9 10 11 12
| import office
stats = office.code.count_lines( folder='代码文件夹', extensions=['.py', '.js', '.java'] )
for ext, count in stats.items(): print(f'{ext}: {count} 行')
print(f'总计: {sum(stats.values())} 行')
|
3、自动整理代码结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import os
def organize_code(): """整理代码文件夹""" folder = '代码文件夹' folders = ['src', 'test', 'docs', 'config', 'lib'] for f in folders: path = os.path.join(folder, f) os.makedirs(path, exist_ok=True) for file in os.listdir(folder): src = os.path.join(folder, file) if not os.path.isfile(src): continue if file.endswith('.py'): dst = os.path.join(folder, 'src', file) shutil.move(src, dst) elif file.startswith('test_'): dst = os.path.join(folder, 'test', file) shutil.move(src, dst) elif file.endswith('.md'): dst = os.path.join(folder, 'docs', file) shutil.move(src, dst) print('代码整理完成!')
organize_code()
|
4、代码格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import os import autopep8
def format_code(folder): """自动格式化Python代码""" for root, dirs, files in os.walk(folder): for file in files: if file.endswith('.py'): filepath = os.path.join(root, file) with open(filepath, 'r', encoding='utf-8') as f: content = f.read() formatted = autopep8.fix_code(content) with open(filepath, 'w', encoding='utf-8') as f: f.write(formatted) print(f'已格式化: {filepath}')
format_code('代码文件夹')
|
5、实战案例:每日代码备份脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import office import shutil import schedule from datetime import datetime import time
def daily_backup(): """每日代码备份""" today = datetime.now().strftime('%Y-%m-%d') projects = [ 'C:\\代码\\项目A', 'C:\\代码\\项目B', 'C:\\代码\\项目C' ] backup_base = f'D:\\每日备份\\{today}' os.makedirs(backup_base, exist_ok=True) for project in projects: project_name = os.path.basename(project) dst = os.path.join(backup_base, project_name) if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(project, dst) print(f'已备份: {project_name}') print(f'今日备份完成: {today}')
schedule.every().day.at('22:00').do(daily_backup)
while True: schedule.run_pending() time.sleep(60)
|
6、实战案例:生成代码统计报告
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import office from datetime import datetime
def generate_code_report(folder): """生成代码统计报告""" import os from collections import defaultdict stats = defaultdict(int) total_lines = 0 total_files = 0 for root, dirs, files in os.walk(folder): for file in files: if '.' in file: ext = '.' + file.split('.')[-1] stats[f'{ext}_count'] = stats.get(f'{ext}_count', 0) + 1 try: filepath = os.path.join(root, file) with open(filepath, 'r', encoding='utf-8') as f: lines = len(f.readlines()) stats[f'{ext}_lines'] = stats.get(f'{ext}_lines', 0) + lines total_lines += lines total_files += 1 except: pass report = [['文件类型', '文件数', '代码行数']] exts = set(k.split('_')[0] for k in stats if k.endswith('_count')) for ext in sorted(exts): report.append([ext, stats[f'{ext}_count'], stats[f'{ext}_lines']]) report.append(['总计', total_files, total_lines]) today = datetime.now().strftime('%Y-%m-%d') office.excel.write(path=f'代码统计_{today}.xlsx', data=report) print(f'报告已生成!总计 {total_files} 个文件,{total_lines} 行代码')
generate_code_report('代码文件夹')
|
7、常见问题
Q:备份太慢怎么办?
A:可以只备份修改过的文件:
1 2 3 4 5 6 7 8 9 10 11
| import os from datetime import datetime
def backup_modified(src, dst, days=1): threshold = datetime.now().timestamp() - days * 86400 for root, dirs, files in os.walk(src): for file in files: path = os.path.join(root, file) if os.path.getmtime(path) > threshold: ...
|
Q:代码格式化有风险吗?
A:建议先提交到Git,再格式化,方便回滚。
8、下讲预告
学会了代码管理,下一讲我们学 数据库基础:用Python操作数据库。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!