当前位置:首页>python>Python OS模块酷炫玩法指南

Python OS模块酷炫玩法指南

  • 2026-06-29 22:39:03
Python OS模块酷炫玩法指南

🐍 Python OS模块酷炫玩法指南

作者:厦门张老师
日期:2026年6月
标签:Python、自动化、效率工具


🌟 目录

  1. 创建专属文件夹
  2. 统计目录信息
  3. 批量重命名
  4. 遍历目录树
  5. 每日打卡程序
  6. 文件整理大师
  7. 系统信息侦探
  8. 桌面壁纸切换器
  9. 文件加密保险箱
  10. 自动生日提醒
  11. 🚀 程序启动器
  12. 🌐 一键网页浏览器
  13. 📁 文件资源管理器
  14. 🎵 音乐播放器控制
  15. ⏰ 定时任务管理器
  16. 📸 截屏大师
  17. 🔍 进程监控器
  18. 🖥️ 电脑远程控制
  19. 📧 自动发送邮件
  20. 🔄 文件对比工具
  21. 📤 目录同步工具
  22. 🔎 文件查找工具
  23. 💾 磁盘空间分析
  24. 📋 日志文件分析

📦 准备工作

安装依赖库

# 核心依赖(Windows用户必装)
pip install pywin32 Pillow cryptography

# 截图功能(可选)
pip install pyscreenshot mss

环境要求

  • Python 3.6+
  • Windows 10/11(部分功能仅支持Windows)
  • 管理员权限(部分操作需要)

平台兼容性说明

功能
Windows
macOS
Linux
文件操作
进程管理
⚠️
⚠️
语音播报
系统控制
⚠️
⚠️

⚠️ 注意:带 ⚠️ 的功能需要根据操作系统调整命令,带 ❌ 的功能仅Windows可用


📁 创建专属文件夹

功能介绍

一键创建你的专属文件夹结构,让文件管理更有序!

代码实现

import os

defcreate_folders():
"""创建专属文件夹结构"""
# 主文件夹
    base_dir = "我的秘密基地"

# 检查主文件夹是否存在
ifnot os.path.exists(base_dir):
        os.mkdir(base_dir)
        print(f"🎉 {base_dir} 创建成功!")
else:
        print(f"⚠️ {base_dir} 已经存在啦")

# 创建子文件夹列表
    sub_folders = ["学习资料""电影""游戏存档""表情包""工作文档"]

for folder in sub_folders:
        folder_path = os.path.join(base_dir, folder)
# 使用 makedirs 可以创建多层目录
        os.makedirs(folder_path, exist_ok=True)
        print(f"📁 已创建: {folder_path}")

# 创建嵌套文件夹
    nested_path = os.path.join(base_dir, "学习资料""Python")
    os.makedirs(nested_path, exist_ok=True)
    print(f"📁 已创建嵌套文件夹: {nested_path}")

defcreate_project_structure(project_name):
"""创建标准项目结构"""
    structure = [
f"{project_name}/src",
f"{project_name}/tests",
f"{project_name}/docs",
f"{project_name}/data",
f"{project_name}/config",
f"{project_name}/scripts"
    ]

for path in structure:
        os.makedirs(path, exist_ok=True)
        print(f"📁 {path}")

# 创建初始文件
    init_file = os.path.join(project_name, "src""__init__.py")
with open(init_file, "w", encoding="utf-8"as f:
        f.write("# 项目初始化文件")
    print(f"📄 已创建: {init_file}")

if __name__ == "__main__":
# 创建个人文件夹
    create_folders()

# 创建项目结构
# create_project_structure("my_new_project")

运行效果

🎉 我的秘密基地 创建成功!
📁 已创建: 我的秘密基地/学习资料
📁 已创建: 我的秘密基地/电影
📁 已创建: 我的秘密基地/游戏存档
📁 已创建: 我的秘密基地/表情包
📁 已创建: 我的秘密基地/工作文档
📁 已创建嵌套文件夹: 我的秘密基地/学习资料/Python

📊 统计目录信息

功能介绍

像侦探一样探索目录,统计文件数量和大小!

代码实现

import os

defexplore_directory(path):
"""探索目录并统计信息"""
    print(f"🔍 正在探索目录:{path}")
    print("-" * 30)

    total_files = 0
    total_size = 0
    file_types = {}

# 遍历目录
for item in os.listdir(path):
        item_path = os.path.join(path, item)

if os.path.isfile(item_path):
            file_size = os.path.getsize(item_path)
            total_files += 1
            total_size += file_size

# 统计文件类型
            _, ext = os.path.splitext(item)
            ext = ext.lower()
            file_types[ext] = file_types.get(ext, 0) + 1

            print(f"📄 {item} - {file_size} 字节")

elif os.path.isdir(item_path):
            print(f"📂 {item}/")

    print("-" * 30)
    print(f"📊 统计结果:")
    print(f"   文件总数:{total_files}")
    print(f"   总大小:{total_size/1024:.2f} KB ({total_size/1024/1024:.2f} MB)")

if file_types:
        print("\n📈 文件类型分布:")
for ext, count in sorted(file_types.items(), key=lambda x: x[1], reverse=True):
            print(f"   {ext}{count} 个")

defget_directory_size(path):
"""递归计算目录大小"""
    total_size = 0

for root, dirs, files in os.walk(path):
for file in files:
            file_path = os.path.join(root, file)
try:
                total_size += os.path.getsize(file_path)
except:
pass

return total_size

if __name__ == "__main__":
# 探索当前目录
    explore_directory(".")

# 计算目录总大小
# size = get_directory_size(".")
# print(f"\n📁 当前目录总大小:{size/1024/1024:.2f} MB")

运行效果

🔍 正在探索目录:.
------------------------------
📂 我的秘密基地/
📄 report.pdf - 204800 字节
📄 notes.txt - 1024 字节
📄 image.png - 102400 字节
------------------------------
📊 统计结果:
   文件总数:3
   总大小:300.00 KB (0.29 MB)

📈 文件类型分布:
   .pdf: 1 个
   .txt: 1 个
   .png: 1 个

✏️ 批量重命名

功能介绍

给文件批量编号,让你的文件井然有序!

代码实现

import os

defbatch_rename(folder, prefix="file_", start_num=1):
"""批量重命名文件夹中的文件"""
    print(f"🔄 正在重命名 {folder} 中的文件...")

# 获取文件夹中的所有文件
    files = []
for item in os.listdir(folder):
        item_path = os.path.join(folder, item)
if os.path.isfile(item_path):
            files.append(item)

ifnot files:
        print("❌ 文件夹中没有文件")
return

# 按名称排序
    files.sort()

# 批量重命名
    counter = start_num
for filename in files:
# 获取文件扩展名
        name, ext = os.path.splitext(filename)

# 新文件名
        new_name = f"{prefix}{counter:03d}{ext}"
        old_path = os.path.join(folder, filename)
        new_path = os.path.join(folder, new_name)

# 重命名
        os.rename(old_path, new_path)
        print(f"✅ {filename} → {new_name}")
        counter += 1

    print(f"\n✨ 完成!共重命名 {counter - start_num} 个文件")

defrename_by_date(folder):
"""按修改日期重命名文件"""
    print(f"📅 按日期重命名 {folder} 中的文件...")

    files_with_dates = []
for item in os.listdir(folder):
        item_path = os.path.join(folder, item)
if os.path.isfile(item_path):
            mtime = os.path.getmtime(item_path)
            files_with_dates.append((mtime, item))

# 按修改时间排序
    files_with_dates.sort()

    counter = 1
for mtime, filename in files_with_dates:
        _, ext = os.path.splitext(filename)
        new_name = f"photo_{counter:03d}{ext}"
        os.rename(os.path.join(folder, filename), 
                  os.path.join(folder, new_name))
        print(f"✅ {filename} → {new_name}")
        counter += 1

if __name__ == "__main__":
# 批量重命名
# batch_rename("表情包", prefix="可爱猫咪_")

# 按日期重命名
    rename_by_date("下载")

运行效果

🔄 正在重命名 表情包 中的文件...
✅ IMG_001.jpg → 可爱猫咪_001.jpg
✅ IMG_002.png → 可爱猫咪_002.png
✅ funny_cat.gif → 可爱猫咪_003.gif

✨ 完成!共重命名 3 个文件

🌲 遍历目录树

功能介绍

递归遍历整个目录树,查看所有文件结构!

代码实现

import os

defwalk_through_directory(path, depth=0):
"""递归遍历目录树"""
    indent = "  " * depth

# 获取目录内容并排序
    items = sorted(os.listdir(path))

for item in items:
        item_path = os.path.join(path, item)

if os.path.isdir(item_path):
            print(f"{indent}📂 {item}/")
# 递归遍历子目录
            walk_through_directory(item_path, depth + 1)
else:
            size = os.path.getsize(item_path)
            print(f"{indent}📄 {item} ({size} bytes)")

deffind_files_by_extension(path, extension):
"""查找指定扩展名的文件"""
    found_files = []

for root, dirs, files in os.walk(path):
for file in files:
if file.lower().endswith(extension.lower()):
                full_path = os.path.join(root, file)
                found_files.append(full_path)
                print(f"✅ {full_path}")

ifnot found_files:
        print(f"❌ 未找到 .{extension} 文件")

return found_files

defcount_files_recursively(path):
"""递归统计文件数量"""
    total_files = 0
    total_dirs = 0

for root, dirs, files in os.walk(path):
        total_files += len(files)
        total_dirs += len(dirs)

    print(f"📊 目录统计:")
    print(f"   总文件数:{total_files}")
    print(f"   总目录数:{total_dirs}")

return total_files, total_dirs

if __name__ == "__main__":
# 遍历目录树
    print("🌲 目录结构:")
    print("-" * 40)
    walk_through_directory(".")

# 查找所有Python文件
# print("\n🔍 查找所有 .py 文件:")
# find_files_by_extension(".", ".py")

# 统计文件数量
# count_files_recursively(".")

运行效果

🌲 目录结构:
----------------------------------------
📂 我的秘密基地/
  📂 学习资料/
    📂 Python/
      📄 notes.txt (1024 bytes)
    📄 Python入门.pdf (204800 bytes)
  📂 电影/
    📄 流浪地球.mp4 (104857600 bytes)
  📂 表情包/
    📄 可爱猫咪_001.jpg (102400 bytes)
📄 report.pdf (51200 bytes)

📅 每日打卡程序

功能介绍

每天自动记录你的打卡情况,生成精美的打卡日历!

代码实现

import os
from datetime import datetime

defcheck_in():
# 获取今天的日期
    today = datetime.now()
    date_str = today.strftime("%Y-%m-%d")
    weekday = today.strftime("%A")

# 打卡记录文件
    check_file = "打卡记录.txt"

# 读取已有记录
    records = []
if os.path.exists(check_file):
with open(check_file, "r", encoding="utf-8"as f:
            records = f.readlines()

# 检查今天是否已打卡
    today_record = f"✅ {date_str} ({weekday})\n"
if today_record in records:
        print("😎 今日已打卡!坚持就是胜利!")
else:
        records.append(today_record)
with open(check_file, "w", encoding="utf-8"as f:
            f.writelines(records)
        print(f"🎉 打卡成功!今天是 {date_str}")
        print(f"📊 累计打卡 {len(records)} 天")

# 显示连续打卡天数
    consecutive_days = 0
    temp_date = today
whileTrue:
        temp_str = temp_date.strftime("%Y-%m-%d")
if any(temp_str in record for record in records):
            consecutive_days += 1
            temp_date = temp_date.replace(day=temp_date.day-1)
else:
break
    print(f"🔥 连续打卡 {consecutive_days} 天!")

if __name__ == "__main__":
    check_in()

运行效果

🎉 打卡成功!今天是 2026-06-15
📊 累计打卡 15 天
🔥 连续打卡 7 天!

使用技巧

  • 设置Windows定时任务,每天自动运行
  • 配合微信/钉钉机器人,打卡成功后发送通知

🗂️ 文件整理大师

功能介绍

自动整理下载文件夹,按类型分类归档!

代码实现

import os
import shutil

deforganize_downloads():
    downloads_path = os.path.expanduser("~/Downloads")
    categories = {
"图片": [".jpg"".png"".gif"".svg"".webp"],
"文档": [".pdf"".doc"".docx"".txt"".xlsx"".pptx"],
"压缩包": [".zip"".rar"".7z"".tar"],
"视频": [".mp4"".mov"".avi"".mkv"],
"音乐": [".mp3"".wav"".flac"],
"安装包": [".exe"".msi"".dmg"".apk"]
    }

# 创建分类文件夹
for category in categories.keys():
        category_path = os.path.join(downloads_path, category)
        os.makedirs(category_path, exist_ok=True)

# 遍历并移动文件
    moved_count = 0
for filename in os.listdir(downloads_path):
        file_path = os.path.join(downloads_path, filename)

if os.path.isfile(file_path):
            _, ext = os.path.splitext(filename)
            ext = ext.lower()

for category, extensions in categories.items():
if ext in extensions:
                    target_path = os.path.join(downloads_path, category, filename)
                    shutil.move(file_path, target_path)
                    print(f"📦 {filename} → {category}/")
                    moved_count += 1
break

    print(f"\n✨ 整理完成!共移动 {moved_count} 个文件")

if __name__ == "__main__":
    organize_downloads()

运行效果

📦 vacation.jpg → 图片/
📦 report.pdf → 文档/
📦 game.zip → 压缩包/
📦 tutorial.mp4 → 视频/

✨ 整理完成!共移动 4 个文件

🕵️ 系统信息侦探

功能介绍

一键获取系统详细信息,做个电脑侦探!

代码实现

import os
import platform

defsystem_info():
    print("🔍 系统信息侦探启动!")
    print("=" * 40)

# 操作系统信息
    print(f"🖥️ 操作系统: {platform.system()}{platform.release()}")
    print(f"🔢 系统版本: {platform.version()}")
    print(f"🏗️ 系统架构: {platform.machine()}")

# Python信息
    print(f"\n🐍 Python版本: {platform.python_version()}")
    print(f"🐙 Python编译器: {platform.python_compiler()}")

# 当前目录
    print(f"\n📂 当前工作目录: {os.getcwd()}")

# 环境变量
    print("\n🌐 环境变量概览:")
    env_vars = ["PATH""USERNAME""HOME"]
for var in env_vars:
if var in os.environ:
            print(f"  {var}{os.environ[var][:50]}...")

# 目录大小统计
    print("\n📊 当前目录文件统计:")
    total_files = 0
    total_dirs = 0
    total_size = 0

for item in os.listdir("."):
        path = os.path.join(".", item)
if os.path.isfile(path):
            total_files += 1
            total_size += os.path.getsize(path)
elif os.path.isdir(path):
            total_dirs += 1

    print(f"  文件数量: {total_files}")
    print(f"  目录数量: {total_dirs}")
    print(f"  总大小: {total_size / (1024 * 1024):.2f} MB")

    print("\n✅ 侦察完毕!")

if __name__ == "__main__":
    system_info()

运行效果

🔍 系统信息侦探启动!
========================================
🖥️ 操作系统: Windows 10
🔢 系统版本: 10.0.19045
🏗️ 系统架构: AMD64

🐍 Python版本: 3.11.4
🐙 Python编译器: MSC v.1934 64 bit (AMD64)

📂 当前工作目录: D:\workspace

🌐 环境变量概览:
  PATH: C:\Python311\Scripts;...
  USERNAME: John
  HOME: C:\Users\John

📊 当前目录文件统计:
  文件数量: 24
  目录数量: 5
  总大小: 12.35 MB

✅ 侦察完毕!

🖼️ 桌面壁纸切换器

功能介绍

定时随机切换桌面壁纸,让你的桌面每天都有新惊喜!

代码实现

import os
import random
import ctypes
from time import sleep

defset_wallpaper(image_path):
"""设置Windows桌面壁纸"""
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, 3)

defwallpaper_switcher(wallpaper_folder, interval=300):
"""定时切换壁纸"""
    print(f"🎨 壁纸切换器启动!")
    print(f"📂 壁纸文件夹: {wallpaper_folder}")
    print(f"⏱️ 切换间隔: {interval}秒")

# 获取所有图片文件
    image_extensions = [".jpg"".jpeg"".png"".bmp"]
    wallpapers = []

for filename in os.listdir(wallpaper_folder):
        ext = os.path.splitext(filename)[1].lower()
if ext in image_extensions:
            wallpapers.append(os.path.join(wallpaper_folder, filename))

ifnot wallpapers:
        print("❌ 未找到壁纸图片!")
return

    print(f"✨ 发现 {len(wallpapers)} 张壁纸")

whileTrue:
# 随机选择一张壁纸
        selected = random.choice(wallpapers)
        set_wallpaper(selected)
        print(f"🖼️ 已切换壁纸: {os.path.basename(selected)}")
        sleep(interval)

if __name__ == "__main__":
# 设置壁纸文件夹路径
    wallpaper_dir = "C:\\Users\\你的用户名\\Pictures\\Wallpapers"
    wallpaper_switcher(wallpaper_dir, interval=600)  # 每10分钟切换一次

使用说明

  1. 创建一个壁纸文件夹,放入喜欢的图片
  2. 修改代码中的壁纸路径
  3. 运行脚本,壁纸会自动定时切换

🔐 文件加密保险箱

功能介绍

用密码保护你的私密文件,安全又便捷!

代码实现

import os
from cryptography.fernet import Fernet

defgenerate_key(password):
"""从密码生成加密密钥"""
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend

    salt = b'salt_12345'# 固定盐值,实际应用中应随机生成并保存
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
return base64.urlsafe_b64encode(kdf.derive(password.encode()))

defencrypt_file(file_path, password):
"""加密文件"""
    key = generate_key(password)
    fernet = Fernet(key)

with open(file_path, "rb"as f:
        data = f.read()

    encrypted_data = fernet.encrypt(data)

# 创建加密文件
    encrypted_path = file_path + ".encrypted"
with open(encrypted_path, "wb"as f:
        f.write(encrypted_data)

# 删除原文件
    os.remove(file_path)
    print(f"🔒 文件已加密: {encrypted_path}")

defdecrypt_file(encrypted_path, password, output_path=None):
"""解密文件"""
    key = generate_key(password)
    fernet = Fernet(key)

with open(encrypted_path, "rb"as f:
        encrypted_data = f.read()

try:
        decrypted_data = fernet.decrypt(encrypted_data)
except:
        print("❌ 密码错误!")
return

if output_path isNone:
        output_path = encrypted_path[:-10]  # 移除.encrypted后缀

with open(output_path, "wb"as f:
        f.write(decrypted_data)

    print(f"🔓 文件已解密: {output_path}")

if __name__ == "__main__":
import base64

# 加密示例
    encrypt_file("secret.txt""mypassword123")

# 解密示例
    decrypt_file("secret.txt.encrypted""mypassword123")

使用提醒

⚠️ 重要:请务必记住你的密码,丢失后无法恢复加密文件!


🎂 自动生日提醒

功能介绍

提前提醒你好友的生日,再也不用担心忘记!

代码实现

import os
from datetime import datetime

defload_birthdays():
"""加载生日列表"""
    birthdays = []

if os.path.exists("birthdays.txt"):
with open("birthdays.txt""r", encoding="utf-8"as f:
for line in f:
                line = line.strip()
if line andnot line.startswith("#"):
                    name, date_str = line.split(",")
                    birthdays.append({"name": name.strip(), "date": date_str.strip()})

return birthdays

defcheck_birthdays():
"""检查即将到来的生日"""
    today = datetime.now()
    birthdays = load_birthdays()

    print("🎂 生日提醒检查中...")
    print("=" * 30)

    upcoming = []
for person in birthdays:
        birth_date = datetime.strptime(person["date"], "%m-%d")
        this_year_birthday = datetime(today.year, birth_date.month, birth_date.day)

# 计算距离天数
if this_year_birthday < today:
            this_year_birthday = datetime(today.year + 1, birth_date.month, birth_date.day)

        days_left = (this_year_birthday - today).days

if days_left == 0:
            print(f"🎉 今天是 {person['name']} 的生日!快送上祝福!")
elif days_left <= 7:
            print(f"📅 {person['name']} 的生日还有 {days_left} 天")
            upcoming.append(person)

ifnot upcoming andnot any((datetime.strptime(p["date"], "%m-%d").month == today.month and
                                 datetime.strptime(p["date"], "%m-%d").day == today.day) for p in birthdays):
        print("😌 近期没有生日提醒")

return upcoming

defadd_birthday(name, date):
"""添加新生日"""
with open("birthdays.txt""a", encoding="utf-8"as f:
        f.write(f"{name}{date}\n")
    print(f"✅ 已添加 {name} 的生日: {date}")

if __name__ == "__main__":
# 添加生日示例
# add_birthday("张三", "08-15")
# add_birthday("李四", "12-25")

    check_birthdays()

birthdays.txt 格式

# 生日列表格式:姓名, 月-日
张三, 08-15
李四, 12-25
王小明, 03-20

运行效果

🎂 生日提醒检查中...
================================
🎉 今天是张三的生日!快送上祝福!
📅 李四的生日还有 3 天


🚀 程序启动器

功能介绍

一键启动你常用的所有程序,比如微信、QQ、浏览器、开发工具等!

代码实现

import os
import subprocess

deflaunch_app(app_path, app_name=None):
"""启动指定程序"""
try:
        subprocess.Popen(app_path, shell=True)
        name = app_name or os.path.basename(app_path)
        print(f"🚀 {name} 已启动!")
returnTrue
except Exception as e:
        print(f"❌ 启动失败: {e}")
returnFalse

deflaunch_common_apps():
"""启动常用程序集合"""
    print("🎯 一键启动常用程序...")
    print("=" * 40)

    apps = {
"微信""C:\\Program Files\\Tencent\\WeChat\\WeChat.exe",
"QQ""C:\\Program Files\\Tencent\\QQ\\Bin\\QQ.exe",
"VS Code""C:\\Users\\你的用户名\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe",
"Chrome""C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"Notepad""notepad.exe",
"Calculator""calc.exe",
"Paint""mspaint.exe"
    }

    success_count = 0
for name, path in apps.items():
if launch_app(path, name):
            success_count += 1

    print(f"\n✅ 成功启动 {success_count}/{len(apps)} 个程序")

defquick_launch_menu():
"""交互式快速启动菜单"""
    print("🎮 快速启动菜单")
    print("=" * 40)
    print("1. 打开浏览器")
    print("2. 打开IDE")
    print("3. 打开音乐软件")
    print("4. 打开微信")
    print("5. 打开文件夹")
    print("0. 退出")

    choice = input("\n请选择 (0-5): ")

    shortcuts = {
"1": ("浏览器""https://www.baidu.com"),
"2": ("IDE""C:\\Users\\你的用户名\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"),
"3": ("音乐""C:\\Program Files\\Tencent\\QQMusic\\QQMusic.exe"),
"4": ("微信""C:\\Program Files\\Tencent\\WeChat\\WeChat.exe"),
"5": ("文件夹", os.path.expanduser("~/Documents"))
    }

if choice in shortcuts:
        name, target = shortcuts[choice]
if choice == "1":
import webbrowser
            webbrowser.open(target)
else:
            launch_app(target, name)

if __name__ == "__main__":
    launch_common_apps()
# quick_launch_menu()  # 取消注释以使用交互式菜单

运行效果

🎯 一键启动常用程序...
========================================
🚀 微信 已启动!
🚀 Notepad 已启动!
🚀 Calculator 已启动!

✅ 成功启动 3/7 个程序

使用技巧

  • 使用快捷方式路径 .lnk 文件也可以启动程序
  • 配合批处理脚本,创建桌面快捷方式

🌐 一键网页浏览器

功能介绍

自动打开多个网页,阅读新闻、刷微博,一键搞定!

代码实现

import os
import webbrowser
import time

defopen_websites():
"""一键打开多个网站"""
    print("🌐 正在打开你喜欢的网站...")

    websites = [
        ("百度""https://www.baidu.com"),
        ("知乎""https://www.zhihu.com"),
        ("微博""https://weibo.com"),
        ("B站""https://www.bilibili.com"),
        ("GitHub""https://github.com")
    ]

for name, url in websites:
        webbrowser.open(url)
        print(f"✅ 已打开: {name}")
        time.sleep(1)  # 避免同时打开太多页面

    print("\n🎉 所有网站已打开,开始冲浪吧!")

defdaily_news():
"""打开每日新闻网站"""
    news_sites = [
        ("今日头条""https://www.toutiao.com"),
        ("腾讯新闻""https://news.qq.com"),
        ("网易新闻""https://news.163.com"),
        ("36氪""https://36kr.com")
    ]

    print("📰 正在获取今日资讯...")
for name, url in news_sites:
        webbrowser.open(url)

    print(f"✅ 已打开 {len(news_sites)} 个新闻源")

defsearch_google(query):
"""用Google搜索"""
    search_url = f"https://www.google.com/search?q={query}"
    webbrowser.open(search_url)
    print(f"🔍 正在搜索: {query}")

if __name__ == "__main__":
# open_websites()
    search_google("Python os模块教程")

运行效果

🌐 正在打开你喜欢的网站...
✅ 已打开: 百度
✅ 已打开: 知乎
✅ 已打开: B站

🎉 所有网站已打开,开始冲浪吧!

📁 文件资源管理器

功能介绍

用代码打开任意文件夹,打开文件位置,甚至打开特定目录!

代码实现

import os
import subprocess

defopen_folder(path):
"""打开指定文件夹"""
if os.path.exists(path):
        os.startfile(path)
        print(f"📂 已打开文件夹: {path}")
else:
        print(f"❌ 路径不存在: {path}")

defopen_file_location(file_path):
"""打开文件所在目录并选中该文件"""
if os.path.exists(file_path):
        subprocess.run(['explorer''/select,', file_path])
        print(f"🎯 已定位文件: {file_path}")
else:
        print(f"❌ 文件不存在: {file_path}")

defcreate_and_open_folder():
"""创建新文件夹并打开"""
    folder_name = input("请输入文件夹名称: ")

ifnot os.path.exists(folder_name):
        os.makedirs(folder_name)
        print(f"✅ 已创建文件夹: {folder_name}")

    open_folder(folder_name)

defquick_open_folders():
"""快速打开常用文件夹"""
    common_paths = {
"桌面": os.path.expanduser("~/Desktop"),
"下载": os.path.expanduser("~/Downloads"),
"文档": os.path.expanduser("~/Documents"),
"图片": os.path.expanduser("~/Pictures"),
"音乐": os.path.expanduser("~/Music"),
"视频": os.path.expanduser("~/Videos"),
"此电脑""::{20D04FE0-3AEA-1069-A2D8-08002B30309D}",
"控制面板""::{21EC2020-3AEA-1069-A2DD-08002B30309D}",
"回收站""::{645FF040-5081-101B-9F08-00AA002F954E}"
    }

    print("📁 常用文件夹")
    print("=" * 40)
for i, (name, path) in enumerate(common_paths.items(), 1):
        print(f"{i}{name}")

    choice = int(input("\n请选择 (1-9): "))
    name, path = list(common_paths.items())[choice - 1]
    open_folder(path)

if __name__ == "__main__":
# 打开当前目录
    open_folder(".")

# 或打开特定文件位置
# open_file_location("C:\\test.txt")

# 快速打开常用文件夹
# quick_open_folders()

运行效果

📂 已打开文件夹: D:\workspace
📁 常用文件夹
========================================
1. 桌面
2. 下载
3. 文档
4. 图片
5. 音乐
6. 视频
7. 此电脑
8. 控制面板
9. 回收站

🎵 音乐播放器控制

功能介绍

用Python控制音乐播放,上一首、下一首、调音量,全自动!

代码实现

import os
import subprocess
import time

defplay_music_folder(folder_path):
"""播放文件夹中的所有音乐"""
    music_extensions = [".mp3"".wav"".flac"".m4a"".ogg"]
    music_files = []

for root, dirs, files in os.walk(folder_path):
for file in files:
if any(file.lower().endswith(ext) for ext in music_extensions):
                music_files.append(os.path.join(root, file))

if music_files:
# 使用默认播放器打开第一首歌
        os.startfile(music_files[0])
        print(f"🎵 正在播放: {os.path.basename(music_files[0])}")
        print(f"📊 共找到 {len(music_files)} 首歌曲")
else:
        print("❌ 未找到音乐文件")

defcontrol_media_player():
"""模拟媒体控制键"""
# 发送键盘指令到系统
    VK_MEDIA_NEXT_TRACK = 0xB0
    VK_MEDIA_PLAY_PAUSE = 0xB3
    VK_MEDIA_PREV_TRACK = 0xB1

import ctypes

    user32 = ctypes.windll.user32

    print("🎮 媒体控制")
    print("1. 播放/暂停")
    print("2. 下一首")
    print("3. 上一首")
    print("4. 增加音量")
    print("5. 减少音量")

    choice = input("请选择: ")

if choice == "1":
        user32.keybd_event(VK_MEDIA_PLAY_PAUSE, 000)
        print("▶️ 已发送播放/暂停指令")
elif choice == "2":
        user32.keybd_event(VK_MEDIA_NEXT_TRACK, 000)
        print("⏭️ 已发送下一首指令")
elif choice == "3":
        user32.keybd_event(VK_MEDIA_PREV_TRACK, 000)
        print("⏮️ 已发送上一首指令")
elif choice == "4":
# 增加音量
for _ in range(5):
            user32.keybd_event(0xAF000)  # VK_VOLUME_UP
        print("🔊 音量已增加")
elif choice == "5":
# 减少音量
for _ in range(5):
            user32.keybd_event(0xAE000)  # VK_VOLUME_DOWN
        print("🔉 音量已减少")

defcreate_playlist():
"""创建播放列表"""
    music_dir = os.path.expanduser("~/Music")
    playlist = []

for root, dirs, files in os.walk(music_dir):
for file in files:
if file.endswith((".mp3"".wav"".flac")):
                playlist.append(os.path.join(root, file))

# 保存为m3u播放列表
with open("my_playlist.m3u""w", encoding="utf-8"as f:
        f.write("
#EXTM3U\n")
for song in playlist:
            f.write(song + "\n")

    print(f"✅ 已创建播放列表,包含 {len(playlist)} 首歌曲")
    print("📄 播放列表文件: my_playlist.m3u")

if __name__ == "__main__":
# play_music_folder(os.path.expanduser("~/Music"))
# control_media_player()
    create_playlist()

运行效果

🎵 正在播放: 周杰伦 - 晴天.mp3
📊 共找到 128 首歌曲

🎮 媒体控制
1. 播放/暂停
2. 下一首
3. 上一首
4. 增加音量
5. 减少音量
请选择: 2
⏭️ 已发送下一首指令

⏰ 定时任务管理器

功能介绍

设置定时任务,到点自动执行,比如定时关机、定时提醒等!

代码实现

import os
import time
from datetime import datetime

defcountdown_timer(seconds, task="任务"):
"""倒计时器"""
    print(f"⏰ 开始 {task},倒计时 {seconds} 秒")

for i in range(seconds, 0-1):
        mins, secs = divmod(i, 60)
        print(f"\r⏳ {mins:02d}:{secs:02d}", end="", flush=True)
        time.sleep(1)

    print(f"\n🔔 {task} 完成!时间到!")

# 播放提示音
import winsound
    winsound.Beep(1000500)  # 1000Hz, 持续500ms

defschedule_shutdown(seconds):
"""定时关机"""
    print(f"🖥️ 电脑将在 {seconds} 秒后关机")
    os.system(f"shutdown /s /t {seconds}")

defcancel_shutdown():
"""取消关机"""
    os.system("shutdown /a")
    print("✅ 已取消关机计划")

defset_alarm(hour, minute, message="起床啦!"):
"""设置闹钟"""
    print(f"⏰ 闹钟已设置: {hour:02d}:{minute:02d}")

whileTrue:
        now = datetime.now()
if now.hour == hour and now.minute == minute:
            print(f"\n🔔 {message}")

# 语音播报
import win32com.client
            speaker = win32com.client.Dispatch("SAPI.SpVoice")
            speaker.Speak(message)

# 播放提示音
import winsound
for _ in range(3):
                winsound.Beep(1000300)
                time.sleep(0.2)
break

        time.sleep(30)  # 每30秒检查一次

defpomodoro_timer():
"""番茄钟:工作25分钟,休息5分钟"""
    print("🍅 番茄工作法")
    print("=" * 40)

    work_time = 25 * 60# 25分钟
    break_time = 5 * 60# 5分钟

for round_num in range(15):  # 4轮
        print(f"\n📝 第 {round_num} 轮:开始工作!")
        countdown_timer(work_time, "工作时间")

if round_num < 4:  # 最后一轮不需要休息
            print(f"☕ 休息一下!")
            countdown_timer(break_time, "休息时间")

    print("\n🎉 今日任务完成!")

if __name__ == "__main__":
# countdown_timer(10, "测试")
# schedule_shutdown(3600)  # 1小时后关机
# cancel_shutdown()
# set_alarm(7, 30, "起床啦!")
    pomodoro_timer()

运行效果

🍅 番茄工作法
========================================

📝 第 1 轮:开始工作!
⏰ 开始工作时间,倒计时 1500 秒
⏳ 24:59
...

🔔 工作时间完成!
☕ 休息一下!

📸 截屏大师

功能介绍

一键截取屏幕,保存为图片,还可以截取指定区域!

代码实现

import os
from datetime import datetime
import ctypes

deftake_screenshot(save_path=None, full_screen=True):
"""截取屏幕"""
if save_path isNone:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        save_path = f"screenshot_{timestamp}.png"

# 方法1:使用PIL和Pyscreenshot
try:
import pyscreenshot as ImageGrab
        img = ImageGrab.grab()
        img.save(save_path)
        print(f"📸 截图已保存: {save_path}")
return save_path
except ImportError:
pass

# 方法2:使用PIL和mss
try:
import mss
import mss.tools
with mss.mss() as sct:
            sct.shot(output=save_path)
        print(f"📸 截图已保存: {save_path}")
return save_path
except ImportError:
pass

# 方法3:使用win32api(仅Windows)
try:
from PIL import ImageGrab
import win32api

        img = ImageGrab.grab()
        img.save(save_path)
        print(f"📸 截图已保存: {save_path}")
return save_path
except ImportError:
        print("❌ 请安装 pyscreenshot 或 Pillow 库")
returnNone

defcapture_region(x, y, width, height):
"""截取指定区域"""
from PIL import ImageGrab

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    save_path = f"region_{timestamp}.png"

# 截取区域: (left, top, right, bottom)
    region = (x, y, x + width, y + height)
    img = ImageGrab.grab(bbox=region)
    img.save(save_path)

    print(f"📸 区域截图已保存: {save_path}")
    print(f"📐 尺寸: {width}x{height} 像素")
return save_path

defauto_screenshot_monitor(interval=60, duration=3600):
"""自动定时截屏监控"""
    print(f"📹 开始自动截屏监控")
    print(f"⏱️ 每 {interval} 秒截取一次,总时长 {duration} 秒")

    screenshots_dir = "screenshots"
    os.makedirs(screenshots_dir, exist_ok=True)

    start_time = time.time()
    count = 0

while time.time() - start_time < duration:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        save_path = os.path.join(screenshots_dir, f"auto_{timestamp}.png")

        take_screenshot(save_path)
        count += 1

        time.sleep(interval)

    print(f"\n✅ 监控结束,共截取 {count} 张图片")
    print(f"📁 保存位置: {screenshots_dir}/")

defcapture_and_open():
"""截图后自动打开查看"""
    save_path = take_screenshot()
if save_path:
        os.startfile(save_path)

if __name__ == "__main__":
# 截取全屏
# take_screenshot()

# 截取指定区域 (x, y, width, height)
# capture_region(100, 100, 800, 600)

# 截图后打开查看
# capture_and_open()

# 自动监控(截取10张,每张间隔5秒)
    auto_screenshot_monitor(interval=5, duration=50)

运行效果

📸 截图已保存: screenshot_20260615_143052.png
📹 开始自动截屏监控
⏱️ 每 5 秒截取一次,总时长 50 秒
📸 区域截图已保存: region_20260615_143100.png
📐 尺寸: 800x600 像素

✅ 监控结束,共截取 10 张图片
📁 保存位置: screenshots/

依赖安装

pip install Pillow pyscreenshot

🔍 进程监控器

功能介绍

查看正在运行的程序,结束指定进程,监控系统资源!

代码实现

import os
import time
from datetime import datetime

deflist_processes():
"""列出所有运行中的进程"""
    print("📋 当前运行的进程")
    print("=" * 70)
    print(f"{'PID':<10}{'进程名':<30}{'内存(MB)':<15}")
    print("-" * 70)

# 使用tasklist命令
import subprocess
    result = subprocess.run(['tasklist'], capture_output=True, text=True)
    lines = result.stdout.split('\n')

for line in lines[3:]:  # 跳过前几行标题
if line.strip():
            parts = line.split()
if len(parts) >= 5:
                pid = parts[1]
                name = ' '.join(parts[4:6]) if len(parts) > 4else parts[0]
                mem = parts[-2] + ' ' + parts[-1]
                print(f"{pid:<10}{name:<30}{mem:<15}")

deffind_process(process_name):
"""查找指定进程"""
import subprocess

    print(f"🔍 搜索进程: {process_name}")
    result = subprocess.run(['tasklist'], capture_output=True, text=True)

    found = False
for line in result.stdout.split('\n'):
if process_name.lower() in line.lower():
            print(f"✅ 找到: {line.strip()}")
            found = True

ifnot found:
        print(f"❌ 未找到进程: {process_name}")

defkill_process(process_name):
"""结束指定进程"""
import subprocess

    confirm = input(f"确定要结束进程 '{process_name}' 吗?(y/n): ")
if confirm.lower() == 'y':
try:
            subprocess.run(['taskkill''/F''/IM'f'{process_name}.exe'])
            print(f"✅ 进程 {process_name} 已结束")
except Exception as e:
            print(f"❌ 结束进程失败: {e}")

defmonitor_system():
"""监控系统资源使用情况"""
import subprocess

    print("🖥️ 系统资源监控")
    print("=" * 50)

# CPU使用率
    result = subprocess.run(['wmic''cpu''get''loadpercentage'], 
                          capture_output=True, text=True)
    cpu = result.stdout.split('\n')[1].strip()
    print(f"📊 CPU使用率: {cpu}%")

# 内存使用情况
    result = subprocess.run(['wmic''OS''get''FreePhysicalMemory,TotalVisibleMemorySize'],
                          capture_output=True, text=True)
    lines = [l for l in result.stdout.split('\n'if l.strip()]
if len(lines) >= 2:
        free, total = lines[1].split()
        total_mb = int(total) / 1024
        free_mb = int(free) / 1024
        used_mb = total_mb - free_mb
        used_percent = (used_mb / total_mb) * 100

        print(f"📊 内存使用: {used_mb:.0f}/{total_mb:.0f} MB ({used_percent:.1f}%)")
        print(f"💾 可用内存: {free_mb:.0f} MB")

defauto_monitor():
"""持续监控系统直到用户停止"""
    print("📹 开始监控系统 (按 Ctrl+C 停止)")
    print("=" * 50)

try:
whileTrue:
# 清屏
            os.system('cls'if os.name == 'nt'else'clear')

            timestamp = datetime.now().strftime("%H:%M:%S")
            print(f"🕐 监控时间: {timestamp}")
            print("-" * 50)

            monitor_system()

# 显示CPU占用最高的3个进程
            print("\n🔥 CPU占用最高的进程:")
import subprocess
            result = subprocess.run(['tasklist''/FO''CSV''/NH'], 
                                  capture_output=True, text=True)

            time.sleep(5)  # 每5秒更新一次

except KeyboardInterrupt:
        print("\n\n✅ 监控已停止")

if __name__ == "__main__":
# list_processes()
# find_process("chrome")
# kill_process("notepad.exe")
# monitor_system()
    auto_monitor()

运行效果

🖥️ 系统资源监控
==================================================
📊 CPU使用率: 35%
📊 内存使用: 8192/16384 MB (50.0%)
💾 可用内存: 8192 MB

🔥 CPU占用最高的进程:
  chrome.exe     -  450 MB
  code.exe       -  320 MB
  python.exe     -  150 MB

🖥️ 电脑远程控制

功能介绍

用Python远程控制电脑开关机、锁屏、执行命令!

代码实现

import os
import subprocess
import time

deflock_computer():
"""锁定电脑"""
    os.system("rundll32.exe user32.dll,LockWorkStation")
    print("🔒 电脑已锁定")

defrestart_computer():
"""重启电脑"""
    confirm = input("确定要重启电脑吗?(y/n): ")
if confirm.lower() == 'y':
        os.system("shutdown /r /t 5")
        print("🖥️ 电脑将在 5 秒后重启...")

defshutdown_computer():
"""关机"""
    confirm = input("确定要关机吗?(y/n): ")
if confirm.lower() == 'y':
        os.system("shutdown /s /t 5")
        print("🖥️ 电脑将在 5 秒后关机...")

defcancel_shutdown():
"""取消关机"""
    os.system("shutdown /a")
    print("✅ 已取消关机计划")

defopen_cmd_commands():
"""打开CMD并执行命令"""
    commands = [
"ipconfig",           # 查看IP配置
"ipconfig /all",      # 详细IP信息
"ping www.baidu.com"# 测试网络
"netstat -an",        # 查看网络连接
"systeminfo",         # 系统信息
"dir",                # 列出目录
"tasklist",           # 进程列表
    ]

    print("🖥️ CMD命令菜单")
    print("=" * 40)
for i, cmd in enumerate(commands, 1):
        print(f"{i}{cmd}")

    choice = int(input("\n选择命令 (1-7): "))
if1 <= choice <= len(commands):
        os.system("start cmd /k " + commands[choice - 1])

defrun_elevated_command():
"""以管理员权限运行命令"""
import ctypes

# 请求管理员权限
try:
        ctypes.windll.shell32.ShellExecuteW(None"runas""cmd.exe"
"ipconfig /flushdns"None1)
        print("✅ 管理员命令已执行")
except Exception as e:
        print(f"❌ 执行失败: {e}")

defcreate_shortcut_on_desktop():
"""在桌面创建快捷方式"""
import win32com.client

    desktop = os.path.join(os.path.expanduser("~"), "Desktop")

# 创建Python脚本快捷方式
    python = win32com.client.Dispatch("WScript.Shell")
    shortcut = python.CreateShortCut(os.path.join(desktop, "我的脚本.lnk"))
    shortcut.TargetPath = "C:\\Python311\\python.exe"
    shortcut.Arguments = "C:\\path\\to\\your\\script.py"
    shortcut.WorkDirectory = "C:\\path\\to\\your"
    shortcut.Description = "运行我的Python脚本"
    shortcut.Save()

    print(f"✅ 快捷方式已创建: {desktop}\\我的脚本.lnk")

if __name__ == "__main__":
    print("🖥️ 电脑控制面板")
    print("=" * 40)
    print("1. 锁定电脑")
    print("2. 重启电脑")
    print("3. 关机")
    print("4. 取消关机")
    print("5. 运行CMD命令")
    print("6. 创建桌面快捷方式")
    print("0. 退出")

    choice = input("\n请选择: ")

    actions = {
"1": lock_computer,
"2": restart_computer,
"3": shutdown_computer,
"4": cancel_shutdown,
"5": open_cmd_commands,
"6": create_shortcut_on_desktop
    }

if choice in actions:
        actions[choice]()

运行效果

🖥️ 电脑控制面板
========================================
1. 锁定电脑
2. 重启电脑
3. 关机
4. 取消关机
5. 运行CMD命令
6. 创建桌面快捷方式
0. 退出

请选择: 1
🔒 电脑已锁定

📧 自动发送邮件

功能介绍

用Python自动发送邮件,支持附件,可以用于自动化通知!

代码实现

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

defsend_email(to_email, subject, body, attachments=None):
"""发送邮件"""
# 邮箱配置(请替换为你的真实信息)
    from_email = "your_email@example.com"
    password = "your_app_password"# 邮箱授权码

# SMTP服务器配置
    smtp_server = "smtp.gmail.com"
    smtp_port = 587

# 创建邮件
    message = MIMEMultipart()
    message['From'] = from_email
    message['To'] = to_email
    message['Subject'] = subject

# 添加邮件正文
    message.attach(MIMEText(body, 'plain''utf-8'))

# 添加附件
if attachments:
for file_path in attachments:
if os.path.exists(file_path):
with open(file_path, "rb"as attachment:
                    part = MIMEBase('application''octet-stream')
                    part.set_payload(attachment.read())
                    encoders.encode_base64(part)
                    part.add_header(
'Content-Disposition',
f'attachment; filename= {os.path.basename(file_path)}'
                    )
                    message.attach(part)
                print(f"📎 已添加附件: {os.path.basename(file_path)}")

# 发送邮件
try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.login(from_email, password)
        server.send_message(message)
        server.quit()
        print(f"✅ 邮件已发送给: {to_email}")
returnTrue
except Exception as e:
        print(f"❌ 发送失败: {e}")
returnFalse

defsend_daily_report():
"""发送每日报告"""
    today = datetime.now().strftime("%Y-%m-%d")

    subject = f"📊 每日报告 - {today}"
    body = f"""
    📅 日期: {today}

    🌟 今日完成事项:
    1. 完成项目A的开发
    2. 修复了3个Bug
    3. 参加了团队会议

    📈 明日计划:
    1. 继续项目B的开发
    2. 代码评审
    3. 文档更新

    以上是今日的工作报告,请查阅!
    """


    attachments = ["打卡记录.txt"]  # 附件列表

    send_email("boss@example.com", subject, body, attachments)

defbatch_send_emails(recipient_list, subject, body):
"""批量发送邮件"""
    print(f"📤 开始批量发送邮件,共 {len(recipient_list)} 个收件人")

    success_count = 0
for i, recipient in enumerate(recipient_list, 1):
if send_email(recipient, subject, body):
            success_count += 1
        print(f"进度: {i}/{len(recipient_list)}")

    print(f"\n✅ 批量发送完成!成功: {success_count}/{len(recipient_list)}")

defsend_error_alert(error_message):
"""发送错误警报"""
    subject = "🚨 系统错误警报"
    body = f"""
    ⚠️ 检测到系统错误!

    错误信息: {error_message}
    时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}

    请及时处理!
    """


# 发送给自己
    send_email("your_email@example.com", subject, body)

if __name__ == "__main__":
from datetime import datetime

# 发送简单邮件
# send_email(
#     "friend@example.com",
#     "🎉 测试邮件",
#     "这是一封用Python自动发送的邮件!"
# )

# 发送带附件的邮件
# send_email(
#     "friend@example.com",
#     "📎 文件分享",
#     "请查收附件中的文件",
#     attachments=["report.pdf", "data.xlsx"]
# )

# 发送每日报告
    send_daily_report()

运行效果

📤 开始批量发送邮件,共 3 个收件人
📎 已添加附件: 打卡记录.txt
✅ 邮件已发送给: friend1@example.com
进度: 1/3
📎 已添加附件: 打卡记录.txt
✅ 邮件已发送给: friend2@example.com
进度: 2/3

✅ 批量发送完成!成功: 2/3

注意事项

⚠️ 重要提醒

  1. Gmail需要开启"低安全性应用访问"或使用应用专用密码
  2. QQ邮箱、网易邮箱需要开启SMTP服务并获取授权码
  3. 请妥善保管邮箱密码,建议使用环境变量存储

🔄 文件对比工具

功能介绍

对比两个文件的差异,找出内容不同之处!

代码实现

import os

defcompare_files(file1, file2):
"""对比两个文件的内容"""
    print(f"🔍 正在对比文件: {file1} vs {file2}")
    print("=" * 60)

# 检查文件是否存在
ifnot os.path.exists(file1):
        print(f"❌ 文件不存在: {file1}")
return
ifnot os.path.exists(file2):
        print(f"❌ 文件不存在: {file2}")
return

# 读取文件内容
with open(file1, "r", encoding="utf-8"as f:
        lines1 = f.readlines()
with open(file2, "r", encoding="utf-8"as f:
        lines2 = f.readlines()

# 对比行数
if len(lines1) != len(lines2):
        print(f"⚠️ 文件行数不同: {len(lines1)} vs {len(lines2)}")

# 逐行对比
    diff_count = 0
    max_lines = max(len(lines1), len(lines2))

for i in range(max_lines):
        line1 = lines1[i].strip() if i < len(lines1) else""
        line2 = lines2[i].strip() if i < len(lines2) else""

if line1 != line2:
            diff_count += 1
            print(f"\n🔴 第 {i+1} 行不同:")
            print(f"   文件1: '{line1}'")
            print(f"   文件2: '{line2}'")

if diff_count == 0:
        print("✅ 两个文件内容完全相同!")
else:
        print(f"\n📊 共发现 {diff_count} 处不同")

deffind_duplicate_files(folder):
"""查找目录中的重复文件"""
    print(f"🔍 正在查找 {folder} 中的重复文件...")

    file_hashes = {}
    duplicates = []

for root, dirs, files in os.walk(folder):
for file in files:
            file_path = os.path.join(root, file)

# 计算文件MD5哈希
import hashlib
try:
with open(file_path, "rb"as f:
                    file_hash = hashlib.md5(f.read()).hexdigest()

if file_hash in file_hashes:
                    duplicates.append((file_hashes[file_hash], file_path))
else:
                    file_hashes[file_hash] = file_path
except:
pass

if duplicates:
        print("\n🔍 发现重复文件:")
for original, duplicate in duplicates:
            print(f"   📄 {original}")
            print(f"   ↔️ {duplicate}")
            print()
else:
        print("✅ 未发现重复文件")

if __name__ == "__main__":
# 对比两个文件
# compare_files("file1.txt", "file2.txt")

# 查找重复文件
    find_duplicate_files(".")

运行效果

🔍 正在查找 . 中的重复文件...

🔍 发现重复文件:
   📄 D:\workspace\docs\report.pdf
   ↔️ D:\workspace\backup\report.pdf

✅ 未发现其他重复文件

📤 目录同步工具

功能介绍

一键同步两个目录的内容,保持文件一致!

代码实现

import os
import shutil

defsync_directories(source, target):
"""同步源目录到目标目录"""
    print(f"🔄 正在同步: {source} → {target}")
    print("=" * 60)

# 确保目标目录存在
    os.makedirs(target, exist_ok=True)

    copied_count = 0
    updated_count = 0
    skipped_count = 0

for root, dirs, files in os.walk(source):
# 创建对应的目标目录
        rel_path = os.path.relpath(root, source)
        target_dir = os.path.join(target, rel_path)
        os.makedirs(target_dir, exist_ok=True)

for file in files:
            source_file = os.path.join(root, file)
            target_file = os.path.join(target_dir, file)

if os.path.exists(target_file):
# 比较文件修改时间
                source_mtime = os.path.getmtime(source_file)
                target_mtime = os.path.getmtime(target_file)

if source_mtime > target_mtime:
                    shutil.copy2(source_file, target_file)
                    updated_count += 1
                    print(f"🔄 更新: {file}")
else:
                    skipped_count += 1
else:
                shutil.copy2(source_file, target_file)
                copied_count += 1
                print(f"📤 复制: {file}")

    print(f"\n📊 同步完成!")
    print(f"   新增: {copied_count} 个文件")
    print(f"   更新: {updated_count} 个文件")
    print(f"   跳过: {skipped_count} 个文件")

defcreate_backup(source, backup_dir=None):
"""创建目录备份"""
if backup_dir isNone:
from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_dir = f"backup_{timestamp}"

    print(f"📦 正在创建备份: {source} → {backup_dir}")
    shutil.copytree(source, backup_dir)
    print(f"✅ 备份完成!")

if __name__ == "__main__":
# 同步目录
    sync_directories("我的秘密基地""备份/我的秘密基地")

# 创建备份
# create_backup("重要文件")

运行效果

🔄 正在同步: 我的秘密基地 → 备份/我的秘密基地
============================================================
📤 复制: notes.txt
📤 复制: photo.jpg
🔄 更新: report.pdf
📤 复制: data.csv

📊 同步完成!
   新增: 3 个文件
   更新: 1 个文件
   跳过: 5 个文件

🔎 文件查找工具

功能介绍

快速查找包含指定内容的文件,搜索整个目录!

代码实现

import os

defsearch_files_by_name(folder, keyword):
"""按文件名搜索"""
    print(f"🔍 正在搜索文件名包含 '{keyword}' 的文件...")
    found = []

for root, dirs, files in os.walk(folder):
for file in files:
if keyword.lower() in file.lower():
                full_path = os.path.join(root, file)
                found.append(full_path)
                print(f"✅ {full_path}")

ifnot found:
        print(f"❌ 未找到包含 '{keyword}' 的文件")

return found

defsearch_files_by_content(folder, keyword):
"""按文件内容搜索"""
    print(f"🔍 正在搜索内容包含 '{keyword}' 的文件...")
    found = []

for root, dirs, files in os.walk(folder):
for file in files:
            file_path = os.path.join(root, file)

# 只搜索文本文件
            ext = os.path.splitext(file)[1].lower()
if ext in [".txt"".py"".md"".json"".csv"]:
try:
with open(file_path, "r", encoding="utf-8", errors="ignore"as f:
                        content = f.read()
if keyword.lower() in content.lower():
                            found.append(file_path)
                            print(f"✅ {file_path}")
except:
pass

ifnot found:
        print(f"❌ 未找到内容包含 '{keyword}' 的文件")

return found

deffind_large_files(folder, min_size_mb=10):
"""查找大于指定大小的文件"""
    print(f"🔍 正在查找大于 {min_size_mb}MB 的文件...")
    large_files = []

for root, dirs, files in os.walk(folder):
for file in files:
            file_path = os.path.join(root, file)
try:
                size_mb = os.path.getsize(file_path) / (1024 * 1024)
if size_mb > min_size_mb:
                    large_files.append((size_mb, file_path))
except:
pass

# 按大小排序
    large_files.sort(reverse=True)

for size, path in large_files:
        print(f"📦 {path} - {size:.1f} MB")

ifnot large_files:
        print(f"✅ 未找到大于 {min_size_mb}MB 的文件")

if __name__ == "__main__":
# 按文件名搜索
# search_files_by_name(".", "report")

# 按内容搜索
# search_files_by_content(".", "password")

# 查找大文件
    find_large_files(".", min_size_mb=5)

运行效果

🔍 正在查找大于 5MB 的文件...
📦 D:\workspace\movies\video.mp4 - 125.5 MB
📦 D:\workspace\backup\archive.zip - 45.2 MB
📦 D:\workspace\data\large_file.csv - 12.8 MB

💾 磁盘空间分析

功能介绍

分析磁盘空间使用情况,找出占用空间最大的文件和目录!

代码实现

import os

defanalyze_disk_usage(path):
"""分析目录磁盘使用情况"""
    print(f"💾 正在分析: {path}")
    print("=" * 60)

# 获取磁盘总空间和可用空间
    total, used, free = shutil.disk_usage(path)

    print(f"📊 磁盘空间:")
    print(f"   总空间: {total / (1024**3):.1f} GB")
    print(f"   已使用: {used / (1024**3):.1f} GB")
    print(f"   可用: {free / (1024**3):.1f} GB")
    print(f"   使用率: {(used/total)*100:.1f}%")

defget_directory_size(path):
"""计算目录大小"""
    total_size = 0
for root, dirs, files in os.walk(path):
for file in files:
try:
                total_size += os.path.getsize(os.path.join(root, file))
except:
pass
return total_size

deffind_biggest_directories(path, top_n=5):
"""找出最大的N个目录"""
    print(f"\n🔥 最大的 {top_n} 个目录:")

    dir_sizes = []
for item in os.listdir(path):
        item_path = os.path.join(path, item)
if os.path.isdir(item_path):
            size = get_directory_size(item_path)
            dir_sizes.append((size, item))

# 按大小排序
    dir_sizes.sort(reverse=True)

for size, name in dir_sizes[:top_n]:
        print(f"   📂 {name} - {size / (1024**2):.1f} MB")

if __name__ == "__main__":
import shutil

# 分析当前磁盘
    analyze_disk_usage(".")

# 查找最大目录
    find_biggest_directories(".", top_n=10)

运行效果

💾 正在分析: D:\
============================================================
📊 磁盘空间:
   总空间: 465.8 GB
   已使用: 312.4 GB
   可用: 153.4 GB
   使用率: 67.1%

🔥 最大的 10 个目录:
   📂 Games - 120.5 GB
   📂 Movies - 85.3 GB
   📂 Documents - 45.2 GB
   📂 Music - 32.8 GB
   📂 Photos - 28.6 GB

📋 日志文件分析

功能介绍

分析日志文件,统计错误数量,找出问题!

代码实现

import os

defanalyze_log_file(log_path):
"""分析日志文件"""
    print(f"📝 正在分析日志: {log_path}")
    print("=" * 60)

ifnot os.path.exists(log_path):
        print(f"❌ 文件不存在: {log_path}")
return

    error_count = 0
    warning_count = 0
    info_count = 0
    errors = []

with open(log_path, "r", encoding="utf-8", errors="ignore"as f:
for line_num, line in enumerate(f, 1):
            line_lower = line.lower()

if"error"in line_lower:
                error_count += 1
                errors.append((line_num, line.strip()))
elif"warning"in line_lower:
                warning_count += 1
elif"info"in line_lower:
                info_count += 1

    print(f"📊 日志分析结果:")
    print(f"   错误: {error_count} 个")
    print(f"   警告: {warning_count} 个")
    print(f"   信息: {info_count} 个")

if errors:
        print(f"\n🔴 最近的 5 个错误:")
for line_num, error in errors[-5:]:
            print(f"   第 {line_num} 行: {error[:80]}...")

defrotate_logs(log_dir, keep_count=7):
"""日志文件轮转"""
    print(f"🔄 正在轮转日志文件...")

    log_files = []
for file in os.listdir(log_dir):
if file.endswith(".log"):
            log_files.append(os.path.join(log_dir, file))

# 按修改时间排序(旧的在前)
    log_files.sort(key=lambda x: os.path.getmtime(x))

# 删除多余的日志文件
    files_to_delete = log_files[:-keep_count]
for file in files_to_delete:
        os.remove(file)
        print(f"🗑️ 删除: {os.path.basename(file)}")

    print(f"✅ 保留最新的 {keep_count} 个日志文件")

if __name__ == "__main__":
# 分析日志文件
    analyze_log_file("app.log")

# 轮转日志
# rotate_logs("logs/", keep_count=7)

运行效果

📝 正在分析日志: app.log
============================================================
📊 日志分析结果:
   错误: 3 个
   警告: 12 个
   信息: 156 个

🔴 最近的 5 个错误:
   第 1234 行: ERROR - Database connection failed...
   第 1198 行: ERROR - Timeout connecting to API...
   第 1056 行: ERROR - Invalid user input...

🚀 进阶玩法

1. 整合到批处理脚本

创建 daily.bat 文件:

@echo off
echo 🎉 开始每日任务...
python check_in.py
python organize_downloads.py
python check_birthdays.py
echo ✅ 每日任务完成!
pause

2. 设置Windows定时任务

  1. 打开「任务计划程序」
  2. 创建基本任务
  3. 设置触发时间(每天早上9点)
  4. 操作选择「启动程序」
  5. 选择你的Python脚本

3. 配合语音提醒

import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("打卡成功!今天也要加油哦!")

💡 安全提醒

  1. 谨慎删除os.remove() 操作不可逆,请确认后再执行
  2. 权限问题:某些目录需要管理员权限
  3. 路径处理:使用 os.path.join() 避免路径分隔符问题
  4. 加密备份:重要文件加密后记得备份密钥

📝 总结

Python的os模块能帮你完成各种系统操作:

  • ✅ 自动化日常任务
  • ✅ 管理文件和文件夹
  • ✅ 获取系统信息
  • ✅ 增强工作效率

快来试试这些酷炫的操作吧!如果有任何问题或想法,欢迎在评论区留言交流!


关注我,获取更多Python实用技巧! 🐍💻✨

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-07-03 05:25:14 HTTP/2.0 GET : https://f.mffb.com.cn/a/499812.html
  2. 运行时间 : 0.271092s [ 吞吐率:3.69req/s ] 内存消耗:5,027.02kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=2c568105d6df20babacf01e6149a96a5
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000574s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000590s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000671s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.001091s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000510s ]
  6. SELECT * FROM `set` [ RunTime:0.001906s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000744s ]
  8. SELECT * FROM `article` WHERE `id` = 499812 LIMIT 1 [ RunTime:0.008419s ]
  9. UPDATE `article` SET `lasttime` = 1783027514 WHERE `id` = 499812 [ RunTime:0.006874s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000695s ]
  11. SELECT * FROM `article` WHERE `id` < 499812 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.006324s ]
  12. SELECT * FROM `article` WHERE `id` > 499812 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.030794s ]
  13. SELECT * FROM `article` WHERE `id` < 499812 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.017026s ]
  14. SELECT * FROM `article` WHERE `id` < 499812 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.013877s ]
  15. SELECT * FROM `article` WHERE `id` < 499812 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.027327s ]
0.272665s