50个开发必备的Python经典脚本(1-10)

目录

1. 将 JSON 转换为 CSV

安装

2. 密码生成器

3.从多个文件中搜索字符串

4. 获取给定网页的所有链接

安装

5.图像水印

安装

6. 抓取并下载网页上的所有图像

安装

执行脚本

7. 低电量通知

安装

执行脚本

8. 计算你的年龄

执行脚本

9. 按不同类别组织下载文件夹

10.从CSV文件批量发送电子邮件

安装

执行脚本


建议收藏备用

50个开发必备的Python经典脚本(1-10)_第1张图片

1. 将 JSON 转换为 CSV

该脚本会将您的 JSON 数据转换为 CSV 文件。它接受 .json 一个文件作为输入并提供 .csv 该文件作为输出。

安装

pip install json
import jsonif __name__ == '__main__':
    try:
        with open('input.json', 'r') as f:
            data = json.loads(f.read())
        output = ','.join([*data[0]])
        for obj in data:
            output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
        with open('output.csv', 'w') as f:
            f.write(output)
    except Exception as ex:
        print(f'Error: {str(ex)}')

2. 密码生成器

这个简单的 Python 项目使用 random 和 string 包来生成给定长度的随机字符串。

import random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 16
password = "".join(random.sample(total, length))
print(password)

3.从多个文件中搜索字符串

在您选择的文件夹中查找包含提供的字符串的文件。

import os
text = input("input text : ")
path = input("path : ")
# os.chdir(path)
def getfiles(path):
    f = 0
    os.chdir(path)
    files = os.listdir()
    # print(files)
    for file_name in files:
        abs_path = os.path.abspath(file_name)
        if os.path.isdir(abs_path):
            getfiles(abs_path)
        if os.path.isfile(abs_path):
            f = open(file_name, "r")
            if text in f.read():
                f = 1
                print(text + " found in ")
                final_path = os.path.abspath(file_name)
                print(final_path)
                return True
    if f == 1:
        print(text + " not found! ")
        return False

getfiles(path)

4. 获取给定网页的所有链接

该脚本获取来自特定网站的所有链接并将它们保存为文本文件。

安装

pip install beautifulsoup4 requests
import requests as rq
from bs4 import BeautifulSoup

url = input("Enter Link: ")
if ("https" or "http") in url:
    data = rq.get(url)
else:
    data = rq.get("https://" + url)
soup = BeautifulSoup(data.text, "html.parser")
links = []
for link in soup.find_all("a"):
    links.append(link.get("href"))

# Writing the output to a file (myLinks.txt) instead of to stdout
# You can change 'a' to 'w' to overwrite the file each time
with open("myLinks.txt", 'a') as saved:
    print(links[:10], file=saved)

5.图像水印

该项目将拍摄一张照片并在其上添加您选择的水印。

安装

pip install Pillow
import os
from PIL import Image

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")
    # add watermark to your image
    position = base_image.size
    newsize = (int(position[0]*8/100),int(position[0]*8/100))
    # print(position)
    watermark = watermark.resize(newsize)
    # print(newsize)
    # return watermark

    new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20
    # create a new transparent image
    transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
    # paste the original image
    transparent.paste(base_image,(0,0))
    # paste the watermark image
    transparent.paste(watermark,new_position,watermark)
    image_mode = base_image.mode
    print(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)
    print("Saving"+output_image_path+"...")

folder = input("Enter Folder Path:")
watermark = input("Enter Watermark Path:")
os.chdir(folder)
files = os.listdir(os.getcwd())
print(files)

if not os.path.isdir("output"):
    os.mkdir("output")

c = 1
for f in files:
    if os.path.isfile(os.path.abspath(f)):
        if f.endswith(".png") or f.endswith(".jpg"):
            watermark_photo(f,watermark,"output/"+f)

6. 抓取并下载网页上的所有图像

该脚本将利用 selenium 和 beautifulsoup4 包从指定网页下载所有照片。

安装

  1. 我们需要使用 pip python 包管理器安装 selenium 和 beautifulsoup4 pip install selenium beautifulsoup4 。
  2. 然后根据您的 chrome 浏览器版本和操作系统从此处下载 chrome 驱动程序 — ChromeDriver - WebDriver for Chrome
  3. 您必须输入程序要求的 chromedriver 路径。
from selenium import webdriver
import requests as rq
import os
from bs4 import BeautifulSoup
import time

# path= E:\web scraping\chromedriver_win32\chromedriver.exe
path = input("Enter Path : ")

url = input("Enter URL : ")

output = "output"


def get_url(path, url):
    driver = webdriver.Chrome(executable_path=r"{}".format(path))
    driver.get(url)
    print("loading.....")
    res = driver.execute_script("return document.documentElement.outerHTML")

    return res


def get_img_links(res):
    soup = BeautifulSoup(res, "lxml")
    imglinks = soup.find_all("img", src=True)
    return imglinks


def download_img(img_link, index):
    try:
        extensions = [".jpeg", ".jpg", ".png", ".gif"]
        extension = ".jpg"
        for exe in extensions:
            if img_link.find(exe) > 0:
                extension = exe
                break

        img_data = rq.get(img_link).content
        with open(output + "\\" + str(index + 1) + extension, "wb+") as f:
            f.write(img_data)

        f.close()
    except Exception:
        pass


result = get_url(path, url)
time.sleep(60)
img_links = get_img_links(result)
if not os.path.isdir(output):
    os.mkdir(output)

for index, img_link in enumerate(img_links):
    img_link = img_link["src"]
    print("Downloading...")
    if img_link:
        download_img(img_link, index)
print("Download Complete!!")

执行脚本

要运行以下脚本,您必须打开终端进入脚本的根目录,并需要输入以下命令

python3 scrap-img.py

它会询问您刚刚下载的 chrome 驱动程序路径以及您要从中下载图像的 URL。

7. 低电量通知

此 python 脚本显示有关设备电池百分比的通知。

安装

要运行此脚本,我们需要 通过运行以下命令来下载psutil、 py-notifier和 win10tost 。

1. psutil  
    > pip install psutil  

2. pynotifier  
    > pip install py-notifier  

3. win10toast  
    > pip install win10toast
# pip install psutil
import psutil

battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent

if percent <= 30 and plugged!=True:

    # pip install py-notifier
    # pip install win10toast
    from pynotifier import Notification

    Notification(
        title="Battery Low",
        description=str(percent) + "% Battery remain!!",
        duration=5,  # Duration in seconds

    ).send()

执行脚本

打开终端进入脚本文件的根目录并运行以下命令

python3 battery.py

8. 计算你的年龄

该脚本以三种不同的方式打印您的年龄: 、 、 

import time
from calendar import isleap

# judge the leap year
def judge_leap_year(year):
    if isleap(year):
        return True
    else:
        return False


# returns the number of days in each month
def month_days(month, leap_year):
    if month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    elif month in [4, 6, 9, 11]:
        return 30
    elif month == 2 and leap_year:
        return 29
    elif month == 2 and (not leap_year):
        return 28


name = input("input your name: ")
age = input("input your age: ")
localtime = time.localtime(time.time())

year = int(age)
month = year * 12 + localtime.tm_mon
day = 0

begin_year = int(localtime.tm_year) - year
end_year = begin_year + year

# calculate the days
for y in range(begin_year, end_year):
    if (judge_leap_year(y)):
        day = day + 366
    else:
        day = day + 365

leap_year = judge_leap_year(localtime.tm_year)
for m in range(1, localtime.tm_mon):
    day = day + month_days(m, leap_year)

day = day + localtime.tm_mday
print("%s's age is %d years or " % (name, year), end="")
print("%d months or %d days" % (month, day))

执行脚本

执行脚本非常简单!

只需在包含脚本的文件夹中打开终端并输入以下命令:

python3 calculate.py

然后你必须输入姓名和年龄

input your name: XYZ  
input your age: 33   
Output - XYZ's age is 33 years or 406 months or 12328 days

9. 按不同类别组织下载文件夹

这是一个 Python 脚本,可根据扩展名将下载目录中的文件分类到其他文件夹中。

import os
import shutil
os.chdir("E:\downloads")
#print(os.getcwd())

#check number of files in  directory
files = os.listdir()

#list of extension (You can add more if you want)
extentions = {
    "images": [".jpg", ".png", ".jpeg", ".gif"],
    "videos": [".mp4", ".mkv"],
    "musics": [".mp3", ".wav"],
    "zip": [".zip", ".tgz", ".rar", ".tar"],
    "documents": [".pdf", ".docx", ".csv", ".xlsx", ".pptx", ".doc", ".ppt", ".xls"],
    "setup": [".msi", ".exe"],
    "programs": [".py", ".c", ".cpp", ".php", ".C", ".CPP"],
    "design": [".xd", ".psd"]
}
#sort to specific folder depend on extenstions
def sorting(file):
    keys = list(extentions.keys())
    for key in keys:
        for ext in extentions[key]:
            # print(ext)
            if file.endswith(ext):
                return key

#iterat through each file
for file in files:
    dist = sorting(file)
    if dist:
        try:
            shutil.move(file, "../download-sorting/" + dist)
        except:
            print(file + " is already exist")
    else:
        try:
            shutil.move(file, "../download-sorting/others")
        except:
            print(file + " is already exist")

10.从CSV文件批量发送电子邮件

该项目包括一个简单的批量电子邮件脚本,可将相同的消息传递给收件人列表。

安装

该项目仅需要 Python 标准库(更具体地说,是 csv、 email和 smtplib 模块)。

import csv
from email.message import EmailMessage
import smtplib

def get_credentials(filepath):
    with open("credentials.txt", "r") as f:
        email_address = f.readline()
        email_pass = f.readline()
    return (email_address, email_pass)

def login(email_address, email_pass, s):
    s.ehlo()
    # start TLS for security
    s.starttls()
    s.ehlo()
    # Authentication
    s.login(email_address, email_pass)
    print("login")

def send_mail():
    s = smtplib.SMTP("smtp.gmail.com", 587)
    email_address, email_pass = get_credentials("./credentials.txt")
    login(email_address, email_pass, s)
    # message to be sent
    subject = "Welcome to Python"
    body = """Python is an interpreted, high-level,
    general-purpose programming language.\n
    Created by Guido van Rossum and first released in 1991,
    Python's design philosophy emphasizes code readability\n
    with its notable use of significant whitespace"""

    message = EmailMessage()
    message.set_content(body)
    message['Subject'] = subject

    with open("emails.csv", newline="") as csvfile:
        spamreader = csv.reader(csvfile, delimiter=" ", quotechar="|")
        for email in spamreader:
            s.send_message(email_address, email[0], message)
            print("Send To " + email[0])

    # terminating the session
    s.quit()
    print("sent")

if __name__ == "__main__":
    send_mail()

执行脚本

该脚本需要使用两个配置文件:

  • emails.csv 应包含邮件应发送到的电子邮件地址。
  • credentials.txt 应包含您的 SMTP 服务器登录凭据,其中您的用户名和密码位于单独的行上,并且没有额外的空格或装饰。

项目目录包含两个示例文件,您几乎肯定希望并需要更改它们。

一旦你准备好这些文件,你所要做的就是

python Send_emails.py

汇总连接:

50个开发必备的Python经典脚本(1-10)

50个开发必备的Python经典脚本(11-20)

50个开发必备的Python经典脚本(21-30)

50个开发必备的Python经典脚本(31-40)

50个开发必备的Python经典脚本(41-50)

你可能感兴趣的:(学习,python,网络)