10个Python脚本,轻松实现日常任务自动化

发布时间:2024-12-11 18:07

用Python编写简单自动化任务脚本 #生活乐趣# #日常生活趣事# #生活趣味分享# #科技小发明#

Python是一种通用编程语言,以其简单性和易读性而著称。它被广泛应用于从网络开发到数据分析等各个领域。在本文中,我们将探讨10个Python脚本,它们可以自动执行常见任务,让你的生活更轻松。
 

1. 使用Pandas进行数据分析

Pandas是一个功能强大的数据分析库。只需几行代码,你就可以读取、清洗和分析来自CSV文件或数据库等各种来源的数据。下面是一个示例脚本。

import pandas as pd

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

mean = data['column_name'].mean()

print(f"Mean: {mean}")

2. 使用BeautifulSoup进行网页抓取

BeautifulSoup 是一个用于网页抓取的Python库。它可以让你轻松地从网站中提取数据。下面是一个简单的网页抓取脚本。

import requests

from bs4 import BeautifulSoup

url = 'https://example.com'

response = requests.get(url)

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

data = soup.find('div', class_='content')

print(data.text)

3. 文件重命名

当你需要根据特定标准对文件夹中的多个文件进行重命名时,此脚本会非常方便。例如,你可以添加前缀和后缀,或替换文件名中的文本。

import os

folder_path = '/path/to/folder'

for filename in os.listdir(folder_path):

if filename.startswith('prefix_'):

        new_filename = filename.replace('prefix_', 'new_prefix_')

        os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))

4. 使用Pillow调整图像大小

Pillow是一个Python图像处理库,可以简化图像处理。此脚本可以将一批图像调整到指定的分辨率或长宽比。

from PIL import Image

import os

input_folder = '/path/to/images'

output_folder = '/path/to/resized_images'

desired_size = (100, 100)

for filename in os.listdir(input_folder):

with Image.open(os.path.join(input_folder, filename)) as img:

        img.thumbnail(desired_size)

        img.save(os.path.join(output_folder, filename))

5. 使用ReportLab创建PDF

ReportLab是一个使用Python创建PDF文档的库。你可以从文本或HTML内容生成PDF文件。下面是一个基本的示例。

from reportlab.pdfgen import canvas

pdf_file = 'output.pdf'

text = 'Hello, this is a sample PDF.'

c = canvas.Canvas(pdf_file)

c.drawString(100, 750, text)

c.save()

6. 使用smtplib发送电子邮件

如果需要自动发送电子邮件,Python的smtplib库可以提供帮助。此脚本可以帮助你以编程方式发送电子邮件。

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

smtp_server = 'smtp.example.com'

sender_email = 'your_email@example.com'

receiver_email = 'recipient@example.com'

password = 'your_password'

message = MIMEMultipart()

message['From'] = sender_email

message['To'] = receiver_email

message['Subject'] = 'Sample Email Subject'

body = 'This is a sample email message.'

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

with smtplib.SMTP(smtp_server, 587) as server:

    server.starttls()

    server.login(sender_email, password)

    server.sendmail(sender_email, receiver_email, message.as_string())

7. 数据备份脚本

自动备份文件和目录,确保数据安全。

import shutil

source_folder = '/path/to/source_folder'

backup_folder = '/path/to/backup_folder'

shutil.copytree(source_folder, backup_folder)

8. 密码生成器

生成强大、随机的密码以增强安全性。

import random

import string

def generate_password(length=12):

    characters = string.ascii_letters + string.digits + string.punctuation

return ''.join(random.choice(characters) for _ in range(length))

password = generate_password()

print(password)

9. 简单的Web服务器

创建一个基本的HTTP服务器,用于测试和开发目的。

import http.server

import socketserver

port = 8000

with socketserver.TCPServer(('', port), http.server.SimpleHTTPRequestHandler) as httpd:

print(f"Serving at port {port}")

    httpd.serve_forever()

10. 使用SQLite备份和恢复数据库

SQLite是一个轻量级、基于磁盘的数据库。它不需要单独的服务器,使用一种独特的SQL变体。它可用于许多应用程序的内部数据存储,也可以用于在使用更大的数据库(如PostgreSQL或Oracle)之前进行原型设计。

下面是一个使用Python备份和恢复SQLite数据库的示例脚本。

import sqlite3

import shutil

source_db_file = 'source.db'

backup_db_file = 'backup.db'

def backup_database():

try:

        shutil.copy2(source_db_file, backup_db_file)

print("Backup successful.")

except Exception as e:

print(f"Backup failed: {str(e)}")

def restore_database():

try:

        shutil.copy2(backup_db_file, source_db_file)

print("Restore successful.")

except Exception as e:

print(f"Restore failed: {str(e)}")

while True:

print("Options:")

print("1. Backup Database")

print("2. Restore Database")

print("3. Quit")

    choice = input("Enter your choice (1/2/3): ")

if choice == '1':

        backup_database()

elif choice == '2':

        restore_database()

elif choice == '3':

break

else:

print("Invalid choice. Please enter 1, 2, or 3.")

在这段代码中:

backup_database()函数会复制SQLite数据库源文件并将其命名为备份文件。运行此函数可创建数据库备份。

restore_database()函数会将备份文件复制回源文件,从而有效地将数据库恢复到创建备份时的状态。

用户可以选择备份数据库、恢复数据库或退出程序。

你可以调整source_db_file和backup_db_file变量来指定SQLite源文件和备份数据库文件的路径。

以上就是10个实用的Python脚本,可以帮助你自动完成日常任务。

 如果你正在学习Python,那么你需要的话可以,点击这里Python重磅福利:入门&进阶全套学习资料、电子书、软件包、项目源码等等免费分享!或扫描下方CSDN官方微信二维码获娶Python入门&进阶全套学习资料、电子书、软件包、项目源码

 

网址:10个Python脚本,轻松实现日常任务自动化 https://www.yuejiaxmz.com/news/view/445605

相关内容

10个Python脚本,轻松实现日常任务自动化!
10个Python脚本轻松实现日常任务自动化
10个Python脚本,轻松实现日常任务自动化
十个Python脚本,轻松实现日常任务自动化
快快收藏!10个Python脚本,轻松实现日常任务自动化
6个Python脚本,轻松实现日常任务自动化
轻松实现日常任务自动化的6个Python脚本
10 个 Python 脚本轻松自动化你的日常任务
10个Python脚本自动化日常任务
10个Python自动化脚本,让日常任务轻松便捷!

随便看看