


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!

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
