【干货分享】推荐5个可以让你事半功倍的Python自动化脚本
从JSON
数据转化CSV
文件
Python
脚本能够将JSON
数据转化到CSV
文件的表格当中去,我们输入的是带有.json
后缀的文件,输出的是.csv
后缀的表格文件,代码如下import json
def converter(input_file, output_file):
try:
with open(input_file, 'r') as f:
data = json.loads(f.read())
output = ','.join([*data[0]])
for obj in data:
output += f'\n{obj[字段名1]},{obj[字段名2]},{obj[字段名3]}'
with open(output_file, 'w') as f:
f.write(output)
except Exception as ex:
print(f'Error: {str(ex)}')
密码生成器
Python
脚本可能会派的上用场,代码如下import random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 指定的密码的长度
password = "".join(random.sample(total, length))
Python
当中的random
和string
模块来生成指定长度的密码给照片添加水印
def watermark_photo(input_image_path,watermark_image_path,output_image_path):
base_image = Image.open(input_image_path)
watermark = Image.open(watermark_image_path).convert("RGBA")
# 添加水印照片
position = base_image.size
newsize = (int(position[0]*8/100),int(position[0]*8/100))
watermark = watermark.resize(newsize)
new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20
# 创建一个全新的空图片
transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
# 将原先的图片复制粘贴过去
transparent.paste(base_image,(0,0))
# 将水印图片复制过去
transparent.paste(watermark,new_position,watermark)
image_mode = base_image.mode
if image_mode == 'RGB':
transparent = transparent.convert(image_mode)
else:
transparent = transparent.convert('P')
transparent.save(output_image_path,optimize=True,quality=100)
电脑电量不足提醒
import psutil
from pynotifier import Notification
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent
if percent <= 20 and plugged != True:
Notification(
title="Battery Low",
description=str(percent) + "% Battery remain!!",
duration=5, # Duration in seconds
).send()
网站截图
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
url = "https://www.baidu.com"
try:
driver.get(url)
page_width = driver.execute_script('return document.body.scrollWidth')
page_height = driver.execute_script('return document.body.scrollHeight')
driver.set_window_size(page_width, page_height)
driver.save_screenshot('screenshot.png')
driver.quit()
print("SUCCESS")
except IndexError:
print('Usage: %s URL' % url)
各位伙伴们好,詹帅本帅搭建了一个个人博客和小程序,汇集各种干货和资源,也方便大家阅读,感兴趣的小伙伴请移步小程序体验一下哦!(欢迎提建议)
推荐阅读
评论