百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

20个日常工作常用的Python脚本 简单的python脚本

off999 2024-12-28 14:43 23 浏览 0 评论

知识星球:写代码那些事

----

如果你有收获|欢迎|点赞|关注|转发

----

这里会定期更新|大厂的开发|架构|方案设计

这里也会更新|如何摸鱼|抓虾

欢迎来到写代码那些事!当涉及到日常工作的自动化和批处理任务时,Python可以成为你的得力助手。以下是一些常用的Python脚本示例,可以帮助你在日常工作中提高效率:

1. 批量文件重命名:

import os

folder_path = '/path/to/folder'
new_prefix = 'new_prefix'

for filename in os.listdir(folder_path):
    if filename.endswith('.txt'):
        new_name = f'{new_prefix}_{filename}'
        os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_name))

2. 自动发送邮件:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email):
    smtp_server = 'smtp.example.com'
    smtp_port = 587
    sender_email = 'your_email@example.com'
    sender_password = 'your_password'

    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender_email
    msg['To'] = to_email

    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, to_email, msg.as_string())
    server.quit()

send_email('Hello', 'This is a test email', 'recipient@example.com')

3. 自动备份文件:

import shutil
import datetime

source_folder = '/path/to/source'
backup_folder = '/path/to/backup'

current_date = datetime.datetime.now().strftime('%Y-%m-%d')
backup_path = os.path.join(backup_folder, f'backup_{current_date}')

shutil.copytree(source_folder, backup_path)

4. 网络爬虫:

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))

5. 数据处理和分析:

import pandas as pd

data = pd.read_csv('data.csv')
filtered_data = data[data['sales'] > 1000]
average_sales = filtered_data['sales'].mean()

print('Average Sales:', average_sales)

6. 数据清洗和转换:

import pandas as pd

data = pd.read_csv('data.csv')
cleaned_data = data.dropna()  # 删除缺失值
transformed_data = cleaned_data.apply(lambda x: x * 2)  # 数据转换

transformed_data.to_csv('cleaned_and_transformed_data.csv', index=False)

7. 自动化测试脚本:

import unittest

class TestMathFunctions(unittest.TestCase):
    def test_add(self):
        self.assertEqual(2 + 2, 4)

    def test_multiply(self):
        self.assertEqual(3 * 5, 15)

if __name__ == '__main__':
    unittest.main()

8. 自动化GUI操作:

import pyautogui
import time

# 打开文本编辑器
pyautogui.press('win')
pyautogui.write('notepad')
pyautogui.press('enter')

time.sleep(2)

# 输入文本并保存
pyautogui.write('Hello, World!')
pyautogui.hotkey('ctrl', 's')
time.sleep(1)
pyautogui.write('file_name.txt')
pyautogui.press('enter')

9. 数据库操作脚本:

import sqlite3

conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()

cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 25))
conn.commit()

cursor.execute('SELECT * FROM users')
for row in cursor.fetchall():
    print(row)

conn.close()

10. 文件监控和处理:

import os
import time

folder_path = '/path/to/folder'

while True:
    for filename in os.listdir(folder_path):
        if filename.endswith('.txt'):
            with open(os.path.join(folder_path, filename), 'r') as file:
                content = file.read()
                # 在这里进行文件内容的处理操作
                print(content)
            os.remove(os.path.join(folder_path, filename))
    time.sleep(10)

11. 自动备份数据库:

import subprocess
import datetime

current_date = datetime.datetime.now().strftime('%Y-%m-%d')
backup_file = f'backup_{current_date}.sql'

subprocess.run(['mysqldump', '-u', 'username', '-p', 'database_name', '>', backup_file], shell=True)

12. 日志文件分析:

import re

log_file = 'app.log'
error_pattern = r'ERROR: (.+)'

errors = []

with open(log_file, 'r') as file:
    for line in file:
        match = re.search(error_pattern, line)
        if match:
            errors.append(match.group(1))

for error in errors:
    print(error)

13. 自动化截屏:

import pyautogui
import time

time.sleep(5)
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')

14. 自动化表单填写:

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://example.com')

name_field = browser.find_element_by_id('name')
name_field.send_keys('John Doe')

email_field = browser.find_element_by_id('email')
email_field.send_keys('john@example.com')

submit_button = browser.find_element_by_id('submit')
submit_button.click()

browser.quit()

15. 自动下载文件:

import requests

file_url = 'https://example.com/file.pdf'
response = requests.get(file_url)

with open('downloaded_file.pdf', 'wb') as file:
    file.write(response.content)

16. 日志自动分析:

import re
from collections import Counter

log_file = 'app.log'
error_pattern = r'ERROR: (.+)'

errors = []

with open(log_file, 'r') as file:
    for line in file:
        match = re.search(error_pattern, line)
        if match:
            errors.append(match.group(1))

error_counts = Counter(errors)
for error, count in error_counts.items():
    print(f'{error}: {count} occurrences')

17. 批量图片处理:

from PIL import Image
import os

input_folder = '/path/to/input/folder'
output_folder = '/path/to/output/folder'

for filename in os.listdir(input_folder):
    if filename.endswith('.jpg'):
        img = Image.open(os.path.join(input_folder, filename))
        img.thumbnail((300, 300))
        img.save(os.path.join(output_folder, filename))

18. 自动化表格生成:

import pandas as pd

data = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 22]
})

data.to_excel('data.xlsx', index=False)

19. 定时提醒工具:

import time
from plyer import notification

def set_reminder(message, interval):
    while True:
        time.sleep(interval)
        notification.notify(
            title='Reminder',
            message=message,
            app_name='Reminder App'
        )

reminder_message = 'Take a break and stretch!'
reminder_interval = 3600  # 1 hour

set_reminder(reminder_message, reminder_interval)

20. 文件夹清理脚本:

import os
import shutil

source_folder = '/path/to/source'
destination_folder = '/path/to/destination'

for filename in os.listdir(source_folder):
    if filename.endswith('.txt'):
        shutil.move(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))

相关推荐

如何理解python中面向对象的类属性和实例属性?

类属性和实例属性类属性就是给类对象中定义的属性通常用来记录与这个类相关的特征类属性不会用于记录具体对象的特征类属性的理解:类属性是与类自身相关联的变量,而不是与类的实例关联。它们通...

Java程序员,一周Python入门:面向对象(OOP) 对比学习

Java和Python都是**面向对象编程(OOP)**语言,无非是类、对象、继承、封装、多态。下面我们来一一对比两者的OOP特性。1.类和对象Java和Python都支持面向对象...

松勤技术精选:Python面向对象魔术方法

什么是魔术方法相信大家在使用python的过程中经常会看到一些双下划线开头,双下划线结尾的方法,我们把它统称为魔术方法魔术方法的特征魔术方法都是双下划线开头,双下划线结尾的方法魔术方法都是pytho...

[2]Python面向对象-【3】方法(python3 面向对象)

方法的概念在Python中,方法是与对象相关联的函数。方法可以访问对象的属性,并且可以通过修改对象的属性来改变对象的状态。方法定义在类中,可以被该类的所有对象共享。方法也可以被继承并重载。方法的语法如...

一文带你理解python的面向对象编程(OOP)

面向对象编程(OOP,Object-OrientedProgramming)是一个较难掌握的概念,而Python作为一门面向对象的语言,在学习其OOP特性时,许多人都会对“继承”和“多态”等...

简单学Python——面向对象1(编写一个简单的类)

Python是一种面向对象的编程语言(ObjectOrientedProgramming),在Python中所有的数据类型都是对象。在Python中,也可以自创对象。什么是类呢?类(Class)是...

python进阶突破面向对象——四大支柱

面向对象编程(OOP)有四大基本特性,通常被称为"四大支柱":封装(Encapsulation)、继承(Inheritance)、多态(Polymorphism)和抽象(Abstrac...

Python学不会来打我(51)面向对象编程“封装”思想详解

在面向对象编程(Object-OrientedProgramming,简称OOP)中,“封装(Encapsulation)”是四大核心特性之一(另外三个是继承、多态和抽象),它通过将数据(属性)和...

Python之面向对象:对象属性解析:MRO不够用,补充3个方法

引言在前面的文章中,我们谈及Python在继承关系,尤其是多继承中,一个对象的属性的查找解析顺序。由于当时的语境聚焦于继承关系,所以只是简要提及了属性解析顺序同方法的解析顺序,而方法的解析顺序,在Py...

Python之面向对象:通过property兼顾属性的动态保护与兼容性

引言前面的文章中我们简要提及过关于Python中私有属性的使用与内部“名称混淆”的实现机制,所以,访问私有属性的方法至少有3种做法:1、使用实例对象点操作符的方式,直接访问名称混淆后的真实属性名。2、...

Python之面向对象:私有属性是掩耳盗铃还是恰到好处

引言声明,今天的文章中没有一行Python代码,更多的是对编程语言设计理念的思考。上一篇文章中介绍了关于Python面向对象封装特性的私有属性的相关内容,提到了Python中关于私有属性的实现是通过“...

Python中的私有属性与方法:解锁面向对象编程的秘密

Python中的私有属性与方法:解锁面向对象编程的秘密在Python的广阔世界里,面向对象编程(OOP)是一种强大而灵活的方法论,它帮助我们更好地组织代码、管理状态,并构建可复用的软件组件。而在这个框...

Python 面向对象:掌握类的继承与组合,让你的代码更高效!

引言:构建高效代码的基石Python以其简洁强大的特性,成为众多开发者首选的编程语言。而在Python的面向对象编程(OOP)范畴中,类的继承和组合无疑是两大核心概念。它们不仅能帮助我们实现代码复用,...

python进阶-Day2: 面向对象编程 (OOP)

以下是为Python进阶Day2设计的学习任务,专注于面向对象编程(OOP)的核心概念和高阶特性。代码中包含详细注释,帮助理解每个部分的实现和目的。任务目标:复习OOP基础:类、对象、继...

外婆都能学会的Python教程(二十八):Python面向对象编程(二)

前言Python是一个非常容易上手的编程语言,它的语法简单,而且功能强大,非常适合初学者学习,它的语法规则非常简单,只要按照规则写出代码,Python解释器就可以执行。下面是Python的入门教程介绍...

取消回复欢迎 发表评论: