Python 常用的 50 个提效小脚本

文件和目录管理

批量重命名文件

import osfor filename in os.listdir('.'):    os.rename(filename, filename.replace('old', 'new'))

查找大文件​​​​​​​

import osfor 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 osos.makedirs('dir/subdir/subsubdir', exist_ok=True)

删除空目录​​​​​​​

import osfor 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 shutilshutil.copy('source.txt', 'destination.txt')

移动文件​​​​​​​

import shutilshutil.move('source.txt', 'destination.txt')

读取文件内容​​​​​​​

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 osif os.path.exists('file.txt'):    print("File exists.")else:    print("File does not exist.")

数据处理

读取 CSV 文件​​​​​​​

import csvwith open('data.csv', 'r') as file:    reader = csv.reader(file)    for row in reader:        print(row)

写入 CSV 文件​​​​​​​

import csvdata = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]with open('data.csv', 'w', newline='') as file:    writer = csv.writer(file)    writer.writerows(data)

读取 JSON 文件​​​​​​​

import jsonwith open('data.json', 'r') as file:    data = json.load(file)

写入 JSON 文件​​​​​​​

import jsondata = {'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 requestsresponse = requests.get('https://www.example.com')print(response.text)

解析 HTML 页面​​​​​​​

from bs4 import BeautifulSoupsoup = BeautifulSoup(response.text, 'html.parser')titles = soup.find_all('h1')for title in titles:    print(title.text)

下载图片​​​​​​​

import requestsimg_data = requests.get('http://example.com/image.jpg').contentwith open('image.jpg', 'wb') as handler:    handler.write(img_data)

发送 HTTP POST 请求​​​​​​​

import requestspayload = {'key1': 'value1', 'key2': 'value2'}response = requests.post('https://httpbin.org/post', data=payload)print(response.text)

处理 JSON 响应​​​​​​​

import requestsresponse = requests.get('https://api.example.com/data')data = response.json()print(data)

设置超时时间​​​​​​​

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

处理异常​​​​​​​

import requeststry:    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 requestssession = requests.Session()response = session.get('https://www.example.com')print(response.text)

获取响应头信息

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

设置自定义请求头

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

 

 

自动化任务

定时执行任务

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
import scheduleimport timedef job():    print("I'm working...")schedule.every(10).seconds.do(job)while True:    schedule.run_pending()    time.sleep(1)

发送电子邮件

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
import smtplibfrom email.mime.text import MIMETextmsg = 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 subprocessresult = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)print(result.stdout.decode('utf-8'))

压缩文件

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

解压文件

  •  
  •  
  •  
import zipfilewith zipfile.ZipFile('archive.zip', 'r') as zipf:    zipf.extractall('extracted_files')

监控文件变化

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
import timeimport osimport hashlibdef get_file_hash(filename):    hasher = hashlib.md5()    with open(filename, 'rb') as f:        buf = f.read()        hasher.update(buf)    return hasher.hexdigest()last_hash = Nonewhile True:    current_hash = get_file_hash('file.txt')    if current_hash != last_hash:        print("File has changed!")        last_hash = current_hash    time.sleep(1)

生成随机数

  •  
  •  
  •  
import randomrandom_number = random.randint(1, 100)print(random_number)

生成随机字符串

  •  
  •  
  •  
  •  
import randomimport stringrandom_string = ''.join(random.choices(string.ascii_letters + string.digits, k=12))print(random_string)

生成随机密码

  •  
  •  
  •  
  •  
import randomimport stringpassword = ''.join(random.choices(string.ascii_letters + string.digits, k=12))print(password)

读取环境变量

  •  
  •  
  •  
import osapi_key = os.getenv('API_KEY')print(api_key)

 

 

文字处理

统计单词数

  •  
  •  
  •  
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 = 30formatted_text = f"Name: {name}, Age: {age}"print(formatted_text)

 

 

300?wx_fmt=png&wxfrom=19

测试开发学习交流

测试开发学习交流

757篇原创内容

公众号

 

高级搬砖236

python高级482

测试工程师281

自动化228

自动化测试300

高级搬砖 · 目录

上一篇Pytest的精髓下一篇python socket 模拟 http请求

阅读 2.4万

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值