python中高频小脚本汇合

在开发过程中有些代码,需要经常用到,但是偶尔还是需要查下用法,这里汇集一下,需要的时候直接搬运。

对文件的操作相关

# 读取文件内容
with open('file.txt', 'r') as file:
    content = file.read()

# 写入文件内容
with open('file.txt', 'w') as file:
    file.write('Hello, World!')

# 追加文件内容
with open('file.txt', 'a') as file:
    file.write('\nAppend this line.')

# 检查文件是否存在
import os
if os.path.exists('file.txt'):
    print("File exists.")
else:
    print("File does not exist.")

# 批量重命名文件
import os
for filename in os.listdir('.'):
    os.rename(filename, filename.replace('old', 'new'))

# 查找大文件
import os
for root, dirs, files in os.walk('.'):
    for name in files:
        if os.path.getsize(os.path.join(root, name)) > 1024 * 1024:  # 大于1MB
            print(os.path.join(root, name))

# 创建目录结构
import os
os.makedirs('dir/subdir/subsubdir', exist_ok=True)

# 删除空目录
import os
for root, dirs, files in os.walk('.', topdown=False):
    for name in dirs:
        dir_path = os.path.join(root, name)
        if not os.listdir(dir_path):
            os.rmdir(dir_path)

# 复制文件
import shutil
shutil.copy('source.txt', 'destination.txt')

# 移动文件
import shutil
shutil.move('source.txt', 'destination.txt')

# 读取 CSV 文件
import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 写入 CSV 文件
import csv
data = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

对json的操作相关

# 读取 JSON 文件
import json
with open('data.json', 'r') as file:
    data = json.load(file)

# 写入 JSON 文件
import json
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
    json.dump(data, file)

# 过滤列表中的重复项
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))

# 排序列表
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)

# 反转列表
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))

# 合并多个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2

# 获取列表中的最大值
my_list = [1, 2, 3, 4, 5]
max_value = max(my_list)

# 获取列表中的最小值
my_list = [1, 2, 3, 4, 5]
min_value = min(my_list)

系统相关

# 定时执行任务
import schedule
import time

def job():
    print("I'm working...")

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

while True:
    schedule.run_pending()
    time.sleep(1)

# 发送电子邮件
import smtplib
from email.mime.text import MIMEText

msg = MIMEText('Hello, this is a test email.')
msg['Subject'] = 'Test Email'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'

s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

# 运行系统命令
import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))

# 压缩文件
import zipfile

with zipfile.ZipFile('archive.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    zipf.write('file.txt')

# 解压文件
import zipfile

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted_files')

#读取环境变量
import os
api_key = os.getenv('API_KEY')
print(api_key)

# 监控文件变化
import time
import os
import hashlib

def get_file_hash(filename):
    hasher = hashlib.md5()
    with open(filename, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
    return hasher.hexdigest()

last_hash = None

while True:
    current_hash = get_file_hash('file.txt')
    if current_hash != last_hash:
        print("File has changed!")
        last_hash = current_hash
    time.sleep(1)

字符相关操作

# 统计单词数
text = "This is a test. This is only a test."
word_count = len(text.split())
print(f"Word count: {word_count}")

# 替换字符串
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)

# 分割字符串
text = "apple,banana,orange"
fruits = text.split(',')
print(fruits)

# 连接字符串
fruits = ['apple', 'banana', 'orange']
text = ', '.join(fruits)
print(text)

# 检查字符串是否包含子串
text = "Hello, World!"
if "World" in text:
    print("Found 'World' in the text.")

# 将字符串转换为大写
text = "hello, world!"
upper_text = text.upper()
print(upper_text)

# 将字符串转换为小写
text = "HELLO, WORLD!"
lower_text = text.lower()
print(lower_text)

# 去除字符串首尾空格
text = "   Hello, World!   "
stripped_text = text.strip()
print(stripped_text)

# 去除字符串中所有空格
text = "Hello,   World!"
no_space_text = text.replace(" ", "")
print(no_space_text)

# 格式化字符串
name = "Alice"
age = 30
formatted_text = f"Name: {name}, Age: {age}"
print(formatted_text)

http请求相关

# 获取网页内容
import requests
response = requests.get('https://www.example.com')
print(response.text)

# 解析 HTML 页面
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h1')
for title in titles:
    print(title.text)

# 下载图片
import requests
img_data = requests.get('http://example.com/image.jpg').content
with open('image.jpg', 'wb') as handler:
    handler.write(img_data)

# 发送 HTTP POST 请求
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.text)

# 处理 JSON 响应
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)

# 设置超时时间
import requests

try:
    response = requests.get('https://www.example.com', timeout=5)
except requests.Timeout:
    print("The request timed out")

# 处理异常
import requests

try:
    response = requests.get('https://www.example.com')
    response.raise_for_status()
except requests.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except Exception as err:
    print(f"Other error occurred: {err}")

# 使用会话保持连接
import requests

session = requests.Session()
response = session.get('https://www.example.com')
print(response.text)

# 获取响应头信息
import requests

response = requests.get('https://www.example.com')
print(response.headers)

# 设置自定义请求头
import requests

headers = {'User-Agent': 'MyApp/1.0'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text)

随机数

# 生成随机数
import random
random_number = random.randint(1, 100)
print(random_number)

# 生成随机字符串
import random
import string
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
print(random_string)

# 生成随机密码
import random
import string
password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
print(password)
相关推荐
PyAIGCMaster1 小时前
ubuntu装P104驱动
linux·运维·ubuntu
奈何不吃鱼1 小时前
【Linux】ubuntu依赖安装的各种问题汇总
linux·运维·服务器
icy、泡芙1 小时前
T527-----音频调试
linux·驱动开发·音视频
aherhuo1 小时前
kubevirt网络
linux·云原生·容器·kubernetes
zzzhpzhpzzz1 小时前
Ubuntu如何查看硬件型号
linux·运维·ubuntu
蜜獾云1 小时前
linux firewalld 命令详解
linux·运维·服务器·网络·windows·网络安全·firewalld
o(╥﹏╥)2 小时前
linux(ubuntu )卡死怎么强制重启
linux·数据库·ubuntu·系统安全
娶不到胡一菲的汪大东2 小时前
Ubuntu概述
linux·运维·ubuntu
黄公子学安全2 小时前
Java的基础概念(一)
java·开发语言·python
Yuan_o_2 小时前
Linux 基本使用和程序部署
java·linux·运维·服务器·数据库·后端