Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 自动化

作者:—上花′Ing   发布日期:2025-10-13   浏览:38

# 示例代码:使用Python进行简单的文件夹自动化任务

import os
import shutil

def organize_files(directory):
    """
    自动化整理指定目录下的文件,根据文件扩展名创建相应的文件夹并移动文件。

    参数:
    directory (str): 需要整理的文件夹路径
    """
    # 获取目录下所有文件
    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

    # 遍历文件列表
    for file in files:
        # 获取文件扩展名
        ext = os.path.splitext(file)[1].lower()

        # 如果是空扩展名,则跳过
        if not ext:
            continue

        # 创建对应扩展名的文件夹(如果不存在)
        folder = os.path.join(directory, ext[1:])  # 去掉点号
        if not os.path.exists(folder):
            os.makedirs(folder)

        # 移动文件到对应的文件夹
        src = os.path.join(directory, file)
        dst = os.path.join(folder, file)
        shutil.move(src, dst)
        print(f"Moved {file} to {folder}")

# 使用示例
organize_files("/path/to/your/directory")

解释说明:

  • os 模块:用于与操作系统交互,例如获取文件列表、创建文件夹等。
  • shutil 模块:用于高级文件操作,如移动文件。
  • organize_files 函数:接收一个目录路径作为参数,遍历该目录下的所有文件,并根据文件扩展名创建相应的文件夹,然后将文件移动到对应的文件夹中。
  • os.listdir:列出指定目录下的所有文件和子目录。
  • os.path.isfile:检查路径是否为文件。
  • os.path.splitext:分离文件名和扩展名。
  • os.makedirs:递归创建文件夹。
  • shutil.move:移动文件。

这个脚本可以帮助你自动整理杂乱的文件夹,按照文件类型分类存放。

上一篇:python heapq

下一篇:append在python中的含义

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站