Python中常用脚本集锦分享

 更新时间:2024年11月05日 09:16:49   作者:PythonFun  
这篇文章为大家收集了一些常用Python脚本,作为平时练手使用,也可以作为自己的笔记,希望对大家有一定的帮助

文件和目录管理

复制文件

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

移动文件

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

创建目录结构

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 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))

检查文件是否存在

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

读取文件内容

with open('file.txt', 'r') as file:    
   content = file.read()

写入文件内容

with open('file.txt', 'w') as file:    
    file.write('Hello, World!')

数据处理

读取 CSV 文件

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

写入 CSV 文件

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 文件

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

写入 JSON 文件

import json
 
# 将数据写入 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)

网络请求与爬虫

获取网页内容

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

发送 HTTP POST 请求

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

处理 JSON 响应

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

下载图片

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

自动化任务

定时执行任务

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) 

发送电子邮件

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() 

统计单词数

# 统计字符串中的单词数
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)

连接字符串

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

格式化字符串

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

其他常见功能

生成随机数

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

生成随机密码

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

读取环境变量

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

运行系统命令

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

以上就是Python中常用脚本集锦分享的详细内容,更多关于Python常用脚本的资料请关注脚本之家其它相关文章!

相关文章

  • Python获取B站粉丝数的示例代码

    Python获取B站粉丝数的示例代码

    这篇文章主要介绍了Python获取B站粉丝数的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Python使用re模块正则提取字符串中括号内的内容示例

    Python使用re模块正则提取字符串中括号内的内容示例

    这篇文章主要介绍了Python使用re模块正则提取字符串中括号内的内容,结合实例形式分析了Python使用re模块进行针对括号内容的正则匹配操作,并简单解释了相关修正符与正则语句的用法,需要的朋友可以参考下
    2018-06-06
  • 使用Tensorflow实现可视化中间层和卷积层

    使用Tensorflow实现可视化中间层和卷积层

    今天小编就为大家分享一篇使用Tensorflow实现可视化中间层和卷积层,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • 教你用Python写一个植物大战僵尸小游戏

    教你用Python写一个植物大战僵尸小游戏

    这篇文章主要介绍了教你用Python写一个植物大战僵尸小游戏,文中有非常详细的代码示例,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • Python淘宝秒杀的脚本实现

    Python淘宝秒杀的脚本实现

    这篇文章主要介绍了Python淘宝秒杀的脚本实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • Python中range函数的使用方法

    Python中range函数的使用方法

    这篇文章主要介绍了Python中range函数的使用方法,文章基于Python3环境展开range函数的使用方法,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+JS)

    python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+J

    这篇文章主要介绍了python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+JS),需要的朋友可以参考下
    2020-03-03
  • Python smtp邮件发送模块用法教程

    Python smtp邮件发送模块用法教程

    这篇文章主要介绍了Python smtp邮件发送模块用法教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • python实现统计代码行数的方法

    python实现统计代码行数的方法

    这篇文章主要介绍了python实现统计代码行数的方法,涉及Python中os模块及codecs模块的相关使用技巧,需要的朋友可以参考下
    2015-05-05
  • python 网络编程要点总结

    python 网络编程要点总结

    Python 提供了两个级别访问的网络服务:低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统 Socket 接口的全部方法。高级别的网络服务模块SocketServer, 它提供了服务器中心类,可以简化网络服务器的开发。下面看下该如何使用
    2021-06-06

最新评论