


Share ten super practical Python automation scripts that get twice the result with half the effort
In our daily work and study, we always encounter various problems, many of which are simple and repeated operations over and over again. We might as well use Python scripts to automate processing. Today I will Let me share with you ten advanced Python scripts to help us reduce unnecessary waste of time and improve efficiency in work and study.
Add watermark to photos
There are various codes for adding watermark to photos. The following may be the simplest form:
from PIL import Image from PIL import ImageFont from PIL import ImageDraw def watermark_Image(img_path,output_path, text, pos): img = Image.open(img_path) drawing = ImageDraw.Draw(img) black = (10, 5, 12) drawing.text(pos, text, fill=black) img.show() img.save(output_path) img = '2.png' watermark_Image(img, 'watermarked_2.jpg','Python爱好者集中营', pos=(10, 10))
Detecting similarity of text files
Many times we need to check the similarity of two files to see how much similarity there is. Maybe the following script file can Comes in handy:
from difflib import SequenceMatcher def file_similarity_checker(f1, f2): with open(f1, errors="ignore") as file1, open(f2, errors="ignore") as file2: f1_data = file1.read() f2_data = file2.read() checking = SequenceMatcher(None, f1_data, f2_data).ratio() print(f"These files are {checking*100} % similar") file_1 = "路径1" file_2 = "路径2" file_similarity_checker(file_1, file_2)
Encrypt the file contentEncryption
Sometimes the content of the file in our hands is very is very important and very confidential. We can choose to encrypt it. The code is as follows:
from cryptography.fernet import Fernet def encrypt(filename, key): fernet = Fernet(key) with open(filename, 'rb') as file: original = file.read() encrypted = fernet.encrypt(original) with open(filename, 'wb') as enc_file: enc_file.write(encrypted) key = Fernet.generate_key() filename = "file.txt" encrypt(filename, key)
We generate a key and then encrypt the file content. Of course, this key is used to decrypt the file later. It will come in handy, so the key must be kept well. The decryption code is as follows:
def decrypt(filename, key): fernet = Fernet(key) with open(filename, 'rb') as enc_file: encrypted = enc_file.read() decrypted = fernet.decrypt(encrypted) with open(filename, 'wb') as dec_file: dec_file.write(decrypted) decrypt(filename, key)
In the above script, the key is a randomly generated random number. Of course, the key can also be our own Specified, the code is as follows:
import pyAesCrypt def Encryption(input_file_path, output_file_path, key): pyAesCrypt.encryptFile(input_file_path, output_file_path, key) print("File has been decrypted") def Decryption(input_file_path, output_file_path, key): pyAesCrypt.decryptFile(input_file_path, output_file_path, key) print("File has been decrypted")
Convert photos to PDF
Sometimes we need to convert photos to PDF format, or add photos to PDF files in sequence, the code is as follows:
import os import img2pdf with open("Output.pdf", "wb") as file: file.write(img2pdf.convert([i for i in os.listdir('文件路径') if i.endswith(".jpg")]))
Modify the length and width of the photo
If we want to modify the length and width of the photo, the following code can help. The code is as follows:
from PIL import Image import os def img_resize(file, h, w): img = Image.open(file) Resize = img.resize((h,w), Image.ANTIALIAS) Resize.save('resized.jpg', 'JPEG', quality=90) img_resize("文件路径", 400, 200)
For other operations on photos
In addition to modifying the length and width of the photo above, we also have other operations on the photo, such as blurring the content of the photo:
img = Image.open('1.jpg') blur = img.filter(ImageFilter.BLUR) blur.save('output.jpg')
Flip the photo 90 degrees:
img = Image.open('1.jpg') rotate = img.rotate(90) rotate.save('output.jpg')
To sharpen the photo:
img = Image.open('1.jpg') sharp = img.filter(ImageFilter.SHARPEN) sharp.save('output.jpg')
Flip the photo symmetrically to the left and right, the code is as follows:
img = Image.open('1.jpg') transpose = img.transpose(Image.FLIP_LEFT_RIGHT) transpose.save('output.jpg')
To process the photo in grayscale:
img = Image.open('1.jpg') convert = img.convert('L') convert.save('output.jpg')
Test Network speed
Of course we need to download the dependent modules in advance before starting to test the network speed
pip install speedtest-cli
Then we start to try to test the network speed:
from speedtest import Speedtest def Testing_Speed(net): download = net.download() upload = net.upload() print(f'下载速度: {download/(1024*1024)} Mbps') print(f'上传速度: {upload/(1024*1024)} Mbps') print("开始网速的测试 ...") net = Speedtest() Testing_Speed(net)
Currency exchange rate conversion
For example, we want to see the exchange rate conversion between US dollars and pounds, how many pounds can be converted from 100 US dollars, the code is as follows:
# 导入模块 from currency_converter import CurrencyConverter from datetime import date # 案例一 conv = CurrencyConverter() c = conv.convert(100, 'USD', 'GBP') print(round(c, 2)) # 保留两位小数
Or we want to see the exchange rate between US dollars and euros Exchange rate conversion between 100 U.S. dollars and how many euros can be converted into:
# 案例二 c = conv.convert(100, 'USD', 'EUR', date=date(2022, 3, 30)) print(round(c, 2)) # 44.1
Generate QR code
This includes the generation of QR code and the analysis of QR code. The code is as follows:
import qrcode from PIL import Image from pyzbar.pyzbar import decode def Generate_qrcode(data): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4,) qr.add_data(data) qr.make(fit=True) image = qr.make_image(fill_color="black", back_color="white") image.save("qrcode.png") Generate_qrcode("Python爱好者集中营 欣一")
Let’s take a look at the analysis of the QR code. The code is as follows:
def Decode_Qrcode(file_name): result = decode(Image.open(file_name)) print("Data:", result[0][0].decode()) Decode_Qrcode("文件名")
Make a simple web application
calls the flask module in Python to make a web application , the code is as follows:
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello World!" @app.route("/python") def test(): return "欢迎来到Python爱好者集中营,欣一" if __name__ == "__main__": app.run(debug=True)
The above is the detailed content of Share ten super practical Python automation scripts that get twice the result with half the effort. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
