Python常用脚本集锦

收集了一些常用Python脚本,作为平时练手使用,也可以作为自己的笔记,用到哪个功能可以自己查询一下即可。

文件和目录管理

复制文件

python 复制代码
import shutil

# 复制源文件到目标文件
shutil.copy('source.txt', 'destination.txt')

移动文件

python 复制代码
import shutil

# 移动文件到新的路径
shutil.move('source.txt', 'destination.txt')

创建目录结构

python 复制代码
import os

# 创建多层目录,如果已经存在则不报错
os.makedirs('dir/subdir/subsubdir', exist_ok=True)

删除空目录

python 复制代码
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)

查找大文件

python 复制代码
import os

# 查找当前目录及子目录下大于1MB的文件
for root, dirs, files in os.walk('.'):
    for name in files:
        if os.path.getsize(os.path.join(root, name)) > 1024 * 1024:
            print(os.path.join(root, name))

检查文件是否存在

python 复制代码
import os

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

读取文件内容

python 复制代码
with open('file.txt', 'r') as file:    
   content = file.read()

写入文件内容

python 复制代码
with open('file.txt', 'w') as file:    
    file.write('Hello, World!')

数据处理

读取 CSV 文件

python 复制代码
import csv

# 读取 CSV 文件并打印每一行
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

写入 CSV 文件

python 复制代码
import csv

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

读取 JSON 文件

python 复制代码
import json

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

写入 JSON 文件

python 复制代码
import json

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

过滤列表中的重复项

python 复制代码
# 从列表中去除重复项
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))

排序列表

python 复制代码
# 对列表进行排序
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)

网络请求与爬虫

获取网页内容

python 复制代码
import requests

# 发送 GET 请求并获取网页内容
response = requests.get('https://www.example.com')
print(response.text)

发送 HTTP POST 请求

python 复制代码
import requests

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

处理 JSON 响应

python 复制代码
import requests

# 获取并解析 JSON 响应
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)

下载图片

python 复制代码
import requests

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

自动化任务

定时执行任务

python 复制代码
import schedule
import time

# 定义定时执行的任务
def job():
    print("I'm working...")

# 每10秒执行一次任务
schedule.every(10).seconds.do(job)
while True:
    schedule.run_pending()
    time.sleep(1) 

发送电子邮件

python 复制代码
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() 

文字处理

统计单词数

python 复制代码
# 统计字符串中的单词数
text = "This is a test. This is only a test."
word_count = len(text.split())
print(f"Word count: {word_count}")

替换字符串

python 复制代码
# 替换字符串中的子串
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)

连接字符串

python 复制代码
# 将列表中的字符串连接为一个字符串
fruits = ['apple', 'banana', 'orange']
text = ', '.join(fruits)
print(text)

格式化字符串

python 复制代码
# 使用 f-string 格式化字符串
name = "Alice"
age = 30
formatted_text = f"Name: {name}, Age: {age}"
print(formatted_text)

其他常见功能

生成随机数

python 复制代码
import random

# 生成1到100之间的随机整数
random_number = random.randint(1, 100)
print(random_number)

生成随机密码

python 复制代码
python
复制代码
import random
import string

# 生成随机密码
password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
print(password)

读取环境变量

python 复制代码
import os

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

运行系统命令

python 复制代码
import subprocess

# 运行系统命令并打印输出
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8')) 
相关推荐
昵称画6 小时前
交接班记录电子化:三班之间的信息不漏
开发语言·数据库·人工智能·低代码·php
“AI国潮设计-小江”6 小时前
【AIGC实战】Python+SDXL批量生成“潮汕英歌舞不倒翁”IP | 角色一致性与多场景融合方案,附完整代码
开发语言·人工智能·python·prompt·aigc
Linux_cy6 小时前
服务器管理工具哪个好用?我用了七八个
运维·服务器·javascript·python·ssh·面板·gmssh
MoRanzhi12036 小时前
第6篇(下)· 使用 PyQt5 实现 2048 高性能计算版:统一运行控制与跨模式安全交接
python·pyqt·进程管理·状态机·软件架构·并发控制·数据一致性
code tsunami6 小时前
【无标题】
开发语言·python
缓慢更新7 小时前
审批的加签与会签:多人意见怎么合
android·java·数据库·低代码·rxjava
CodeGL7 小时前
10、Python基础之进程和线程
开发语言·python
跨境联盟7 小时前
大健康实体如何搭建产品差异化:对比普通营养品与合规跨境膳食补充剂服务模式
数据库·ai·健康医疗·健康管理·精准营养
有想法的py工程师7 小时前
PostgreSQL EXPLAIN中的Cost模型分析(random_page_cost参数):优化器眼中的代价世界与执行计划生成
数据库·postgresql
前进的李工8 小时前
飞书企业知识库设计+后端高频八股
数据库·redis·后端·mysql·性能优化·飞书·rag