Python自动化处理日常任务的示例代码

发布时间:2025-09-18 07:03

学习基础的Python编程,可以自动化处理文件和任务,提高效率。 #生活知识# #生活经验# #软件#

 更新时间:2025年01月16日 10:46:57   作者:王子良.  

Python客栈送红包、纸质书

+

目录

1. 自动化文件管理

1.1 批量重命名文件

假设你有一批文件,文件名需要按一定规则批量修改,可以使用 os 和 re 库来实现。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import os

import re

directory = 'C:/path/to/your/files'

files = os.listdir(directory)

for filename in files:

    new_name = re.sub(r'old_pattern', 'new_pattern', filename) 

    os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

print("文件重命名完成!")

1.2 自动分类文件

根据文件扩展名自动将文件分类到不同的文件夹中。

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

import os

import shutil

directory = 'C:/path/to/your/files'

files = os.listdir(directory)

file_types = {

    'images': ['.jpg', '.jpeg', '.png', '.gif'],

    'documents': ['.pdf', '.txt', '.docx'],

    'audio': ['.mp3', '.wav']

}

for folder in file_types:

    if not os.path.exists(os.path.join(directory, folder)):

        os.makedirs(os.path.join(directory, folder))

for filename in files:

    file_path = os.path.join(directory, filename)

    if os.path.isfile(file_path):

        moved = False

        for folder, extensions in file_types.items():

            if any(filename.endswith(ext) for ext in extensions):

                shutil.move(file_path, os.path.join(directory, folder, filename))

                moved = True

                break

        if not moved:

            print(f"文件 {filename} 没有分类!")

print("文件分类完成!")

2. 自动化定时任务

2.1 使用 schedule 库定时执行任务

schedule 是一个 Python 库,专门用于调度定时任务。你可以使用它来设置定时执行的任务。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import schedule

import time

def job():

    print("任务开始执行!")

schedule.every(10).seconds.do(job)

while True:

    schedule.run_pending()

    time.sleep(1)

2.2 使用 APScheduler 执行复杂定时任务

APScheduler 是一个功能更强大的调度任务库,支持多种调度方式。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

from apscheduler.schedulers.blocking import BlockingScheduler

import datetime

def print_time():

    print(f"当前时间:{datetime.datetime.now()}")

scheduler = BlockingScheduler()

scheduler.add_job(print_time, 'interval', minutes=1)

scheduler.start()

3. 自动化发送邮件

使用 smtplib 库,可以自动化发送邮件,比如定时向客户或团队成员发送报告。

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

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email):

    from_email = "your_email@gmail.com"

    password = "your_password"

    msg = MIMEMultipart()

    msg['From'] = from_email

    msg['To'] = to_email

    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    try:

        server = smtplib.SMTP('smtp.gmail.com', 587)

        server.starttls()

        server.login(from_email, password)

        text = msg.as_string()

        server.sendmail(from_email, to_email, text)

        server.quit()

        print("邮件发送成功!")

    except Exception as e:

        print(f"邮件发送失败:{e}")

send_email("自动化报告", "这是自动化发送的邮件内容", "recipient_email@example.com")

4. 自动化网络爬虫

使用 requests 和 BeautifulSoup 库,可以自动化爬取网页内容,并将其存储到文件中。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import requests

from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

title = soup.title.string

print(f"网页标题: {title}")

5. 自动化数据处理

5.1 使用 Pandas 库处理数据

如果你经常需要处理 CSV 文件或 Excel 文件,可以使用 Pandas 库来实现数据的读取、处理和导出。

1

2

3

4

5

6

7

8

9

10

11

12

import pandas as pd

df = pd.read_csv('data.csv')

df_filtered = df[df['column_name'] > 100]

df_filtered.to_csv('filtered_data.csv', index=False)

print("数据处理完成!")

5.2 定时备份数据库

可以通过 Python 脚本定时备份数据库,减少人工干预。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import mysql.connector

import datetime

import os

def backup_database():

    db = mysql.connector.connect(

        host="localhost",

        user="your_user",

        password="your_password",

        database="your_database"

    )

    backup_filename = f"backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"

    os.system(f"mysqldump -u your_user -p'your_password' your_database > {backup_filename}")

    print(f"数据库备份完成!备份文件: {backup_filename}")

backup_database()

6. 自动化图像处理

如果你需要自动处理图像文件(例如,批量调整大小、转换格式等),可以使用 Pillow 库。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from PIL import Image

import os

image_directory = 'C:/path/to/your/images'

files = os.listdir(image_directory)

for filename in files:

    if filename.endswith('.jpg'):

        image_path = os.path.join(image_directory, filename)

        with Image.open(image_path) as img:

            img = img.resize((800, 600)) 

            img.save(os.path.join(image_directory, f"resized_{filename}"))

print("图像处理完成!")

7. 自动化 Web 操作

如果你需要自动化与网页的交互,可以使用 Selenium 来模拟浏览器操作。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from selenium import webdriver

driver = webdriver.Chrome(executable_path="path/to/chromedriver")

driver.get("https://example.com")

button = driver.find_element_by_xpath("//button[@id='submit']")

button.click()

page_content = driver.page_source

print(page_content)

driver.quit()

总结

使用 Python 自动化日常任务可以极大地提高效率并减少重复性工作。通过 Python 中的各种库(如 os、shutil、schedule、smtplib、requests、pandas、Pillow 等),你可以轻松实现文件管理、定时任务、邮件发送、网页爬取、数据处理等多种自动化任务。

到此这篇关于Python自动化处理日常任务的示例代码的文章就介绍到这了,更多相关Python自动化处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

使用Python实现自动化办公的代码示例(邮件、excel)使用Python实现简单的任务自动化Python操作系统的6个自动化脚本小结10个Python办公自动化案例总结Python PyAutoGUI实现自动化任务应用场景示例

原文链接:https://blog.csdn.net/weixin_45710998/article/details/145161280

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 reterry123@163.com 进行投诉反馈,一经查实,立即处理!

网址:Python自动化处理日常任务的示例代码 https://www.yuejiaxmz.com/news/view/1309992

相关内容

10个Python自动化日常任务实战脚本示例
使用Python脚本自动化日常任务的技巧与实战案例
AI助力自动化:利用AI生成BAT脚本与Python代码,简化日常生活任务
用 Python 自动化处理日常任务
Python PyAutoGUI实现自动化任务应用场景示例
利用Python自动化日常任务
自动化运维的魔法:如何用Python简化日常任务
如何利用Python自动化日常任务
【Python】教你彻底了解Python中的自动化任务处理
从零开始构建:Python自定义脚本自动化你的日常任务

随便看看