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

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

off999 2024-12-28 14:43 14 浏览 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 数据分析——利用Pandas进行分组统计

话说天下大势,分久必合,合久必分。数据分析也是如此,我们经常要对数据进行分组与聚合,以对不同组的数据进行深入解读。本章将介绍如何利用Pandas中的GroupBy操作函数来完成数据的分组、聚合以及统计...

python数据分析:介绍pandas库的数据类型Series和DataFrame

安装pandaspipinstallpandas-ihttps://mirrors.aliyun.com/pypi/simple/使用pandas直接导入即可importpandasas...

使用DataFrame计算两列的总和和最大值_[python]

【如果对您有用,请关注并转发,谢谢~~】最近在处理气象类相关数据的空间计算,在做综合性计算的时候,DataFrame针对每列的统计求和、最大值等较为方便,对某行的两列或多列数据进行求和与最大值等的简便...

8-Python内置函数

Python提供了丰富的内置函数,这些函数可以直接使用而无需导入任何模块。以下是一些常用的内置函数及其示例:1-print()1-1-说明输出指定的信息到控制台。1-2-例子2-len()2-1-说...

Python中函数式编程函数: reduce()函数

Python中的reduce()函数是一个强大的工具,它通过连续地将指定的函数应用于序列(如列表)来对序列(如列表)执行累积操作。它是functools模块的一部分,这意味着您需要在使用它之...

万万没想到,除了香农计划,Python3.11竟还有这么多性能提升

众所周知,Python3.11版本带来了较大的性能提升,但是,它具体在哪些方面上得到了优化呢?除了著名的“香农计划”外,它还包含哪些与性能相关的优化呢?本文将带你一探究竟!作者:BeshrKay...

最全python3.11版12类75个内置函数大全

获取全部内置函数:importbuiltins#导入模块yc=[]#异常属性nc=[]#不可调用fn=[]#内置函数defll(ty=builtins):...

软件测试笔试题

测试工程师岗位,3-5年,10-14k1.我司有一款产品,类似TeamViewer,向日葵,mstsc,QQ远程控制产品,一个PC客户端产品,请设想一下测试要点。并写出2.写出常用的SQL语句8条,l...

备战各大互联网巨头公司招聘会,最全Python面试大全,共300题

前言众所周知,越是顶尖的互联网公司在面试这一part的要求就越高,需要你有很好的技术功底、项目经验、一份漂亮的简历,当然还有避免不了的笔试过关。对于Python的工程师来说,全面掌握好有关Python...

经典 SQL 数据库笔试题及答案整理

马上又是金三银四啦,有蛮多小伙伴在跳槽找工作,但对于年限稍短的软件测试工程师,难免会需要进行笔试,而在笔试中,基本都会碰到一道关于数据库的大题,今天这篇文章呢,就收录了下最近学员反馈上来的一些数据库笔...

用Python开发日常小软件,让生活与工作更高效!附实例代码

引言:Python如何让生活更轻松?在数字化时代,编程早已不是程序员的专属技能。Python凭借其简洁易学的特点,成为普通人提升效率、解决日常问题的得力工具。无论是自动化重复任务、处理数据,还是开发个...

太牛了!102个Python实战项目被我扒到了!建议收藏!

挖到宝了!整整102个Python实战项目合集,从基础语法到高阶应用全覆盖,附完整源码+数据集,手把手带你从代码小白变身实战大神!这波羊毛不薅真的亏到哭!超全项目库,学练一站式搞定这份资...

Python中的并发编程

1.Python对并发编程的支持多线程:threading,利用CPU和IO可以同时执行的原理,让CPU不会干巴巴等待IO完成。多进程:multiprocessing,利用多核CPU...

Python 也有内存泄漏?

1.背景前段时间接手了一个边缘视觉识别的项目,大功能已经开发的差不多了,主要是需要是优化一些性能问题。其中比较突出的内存泄漏的问题,而且不止一处,有些比较有代表性,可以总结一下。为了更好地可视化内存...

python爬虫之多线程threading、多进程、协程aiohttp批量下载图片

一、单线程常规下载常规单线程执行脚本爬取壁纸图片,只爬取一页的图片。importdatetimeimportreimportrequestsfrombs4importBeautifu...

取消回复欢迎 发表评论: