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)
相关推荐
EterNity_TiMe_1 分钟前
【论文复现】(CLIP)文本也能和图像配对
python·学习·算法·性能优化·数据分析·clip
长弓聊编程3 分钟前
Linux系统使用valgrind分析C++程序内存资源使用情况
linux·c++
cherub.10 分钟前
深入解析信号量:定义与环形队列生产消费模型剖析
linux·c++
Suyuoa12 分钟前
附录2-pytorch yolov5目标检测
python·深度学习·yolo
梅见十柒33 分钟前
wsl2中kali linux下的docker使用教程(教程总结)
linux·经验分享·docker·云原生
Koi慢热36 分钟前
路由基础(全)
linux·网络·网络协议·安全
传而习乎1 小时前
Linux:CentOS 7 解压 7zip 压缩的文件
linux·运维·centos
我们的五年1 小时前
【Linux课程学习】:进程程序替换,execl,execv,execlp,execvp,execve,execle,execvpe函数
linux·c++·学习
好看资源平台1 小时前
网络爬虫——综合实战项目:多平台房源信息采集与分析系统
爬虫·python
IT果果日记1 小时前
ubuntu 安装 conda
linux·ubuntu·conda