16个好用到爆的Python实用脚本!

以下是16个非常实用的Python脚本示例,每个脚本都有其特定的用途,并且我会附上相应的源码。这些脚本涵盖了数据处理、网络请求、文件操作等多个方面,非常适合初学者和进阶者学习和使用。
在这里插入图片描述

1. 批量重命名文件

import os

def batch_rename(folder_path, prefix):
    for filename in os.listdir(folder_path):
        old_file = os.path.join(folder_path, filename)
        new_file = os.path.join(folder_path, prefix + filename)
        os.rename(old_file, new_file)

# 使用示例
folder_path = 'path/to/your/folder'
prefix = 'new_'
batch_rename(folder_path, prefix)

2. 发送HTTP GET请求

import requests

def send_get_request(url):
    response = requests.get(url)
    return response.text

# 使用示例
url = 'http://example.com'
print(send_get_request(url))

3. 读取CSV文件

import csv

def read_csv(file_path):
    with open(file_path, mode='r', encoding='utf-8') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            print(row)

# 使用示例
file_path = 'path/to/your/file.csv'
read_csv(file_path)

4. 写入CSV文件

import csv

def write_csv(file_path, data):
    with open(file_path, mode='w', encoding='utf-8', newline='') as file:
        csv_writer = csv.writer(file)
        for row in data:
            csv_writer.writerow(row)

# 使用示例
file_path = 'path/to/your/file.csv'
data = [['name', 'age'], ['Alice', 30], ['Bob', 25]]
write_csv(file_path, data)

5. 读取JSON文件

import json

def read_json(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return json.load(file)

# 使用示例
file_path = 'path/to/your/file.json'
data = read_json(file_path)
print(data)

6. 写入JSON文件

import json

def write_json(file_path, data):
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)

# 使用示例
file_path = 'path/to/your/file.json'
data = {'name': 'Alice', 'age': 30}
write_json(file_path, data)

7. 简单的网页爬虫

import requests
from bs4 import BeautifulSoup

def simple_web_crawler(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    titles = soup.find_all('title')
    for title in titles:
        print(title.text)

# 使用示例
url = 'http://example.com'
simple_web_crawler(url)

8. 计算文件夹大小

import os

def calculate_folder_size(folder_path):
    total_size = 0
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            total_size += os.path.getsize(file_path)
    return total_size

# 使用示例
folder_path = 'path/to/your/folder'
print(f'Folder size: {calculate_folder_size(folder_path)} bytes')

9. 检查网站是否可访问

import requests

def check_website_availability(url):
    try:
        response = requests.get(url)
        return response.status_code == 200
    except requests.ConnectionError:
        return False

# 使用示例
url = 'http://example.com'
print(check_website_availability(url))

10. 简单的数据清洗(去除空格和换行符)

def clean_data(data):
    return [item.strip() for item in data if item.strip()]

# 使用示例
data = [' Alice ', 'Bob\n', 'Charlie', '']
cleaned_data = clean_data(data)
print(cleaned_data)

11. 合并多个Excel文件

import pandas as pd

def merge_excel_files(folder_path):
    merged_df = pd.DataFrame()
    for file in os.listdir(folder_path):
        if file.endswith('.xlsx'):
            file_path = os.path.join(folder_path, file)
            df = pd.read_excel(file_path)
            merged_df = pd.concat([merged_df, df], ignore_index=True)
    return merged_df

# 使用示例
folder_path = 'path/to/your/excel/files'
merged_data = merge_excel_files(folder_path)
print(merged_data)

12. 提取PDF文件中的文本

import PyPDF2

def extract_text_from_pdf(pdf_path):
    with open(pdf_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfFileReader(file)
        text = ''
        for page_num in range(pdf_reader.numPages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
    return text

# 使用示例
pdf_path = 'path/to/your/file.pdf'
text = extract_text_from_pdf(pdf_path)
print(text)

13. 发送电子邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(sender_email, receiver_email, password, subject, body):
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject
    message.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, password)
    text = message.as_string()
    server.sendmail(sender_email, receiver_email, text)
    server.quit()

# 使用示例
sender_email = 'your_email@gmail.com'
receiver_email = 'receiver_email@gmail.com'
password = 'your_password'
subject = 'Test Email'
body = 'This is a test email.'
send_email(sender_email, receiver_email, password, subject, body)

14. 简单的文本加密和解密(使用Base64)

import base64

def encrypt_text(text):
    return base64.b64encode(text.encode()).decode()

def decrypt_text(encrypted_text):
    return base64.b64decode(encrypted_text).decode()

# 使用示例
text = 'Hello, World!'
encrypted_text = encrypt_text(text)
print(f'Encrypted: {encrypted_text}')
decrypted_text = decrypt_text(encrypted_text)
print(f'Decrypted: {decrypted_text}')

15. 生成随机密码

import random
import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for i in range(length))

# 使用示例
password_length = 12
password = generate_password(password_length)
print(password)

16. 检查密码强度

python
def check_password_strength(password):
    strength = 0
    if len(password) >= 8:
        strength += 1
    if any(char.isdigit() for char in

关于Python学习指南

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!
————————————————

在这里插入图片描述

**全套Python学习资料分享:
👉Python所有方向的学习路线👈

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)

​​​​在这里插入图片描述

👉学习软件

在这里插入图片描述

👉全套PDF电子书

在这里插入图片描述

👉实战案例
在这里插入图片描述

👉Python副业兼职路线&方法👈
学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。

在这里插入图片描述

👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方CSDN官方认证二维码或者点击链接免费领取保证100%免费

在这里插入图片描述

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值