用python写小脚本是一件好玩的事情,因为不是个大活儿,而且能解决眼边前十分繁琐的事情,这种轻松且便宜的代码颇受人民群众的欢迎~有点生活小妙招的意味
大家较为熟知的脚本是用python来做爬虫、抢票、签到、自动回复机器人、批量处理文件等,这些比较常规,还有些较复杂的,比如做物品识别、语义分析、图像处理等,只要你有需求场景,总会想到办法写个脚本去处理它。
github上有个python项目,里面提供了几百个(可能上千)小脚本,涉及到算法、文件、文本、图像、视频、音乐、爬虫、邮件、可视化、系统、下载等各种常用场景的处理脚本。项目地址:https://github.com/geekcomputers/Python
这个项目不是什么牛逼的大程序,而是作者在日常工作和python学习过程中积累的脚本,一个脚本解决一个问题。获得1万9的赞,说明颇有群众基础。
作者在介绍中所说,他并非专业程序员,而是为了解决问题、提高效率写了这些代码。我也是鼓励初学者可以先按照这种模式来学习编程,从解决问题的角度来写代码,把python当作一把锤子,不断找钉子。
分享其中几个脚本:
1、检查主目录中是否存在某文件夹,若不存在则创建文件# Description : Checks to see if a directory exists in the users home directory, if not then create it
import os # Import the OS module
MESSAGE = 'The directory already exists.'
TESTDIR = 'testdir'
try:
home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory
print(home) # Print the location
if not os.path.exists(os.path.join(home, TESTDIR)): # os.path.join() for making a full path safely
os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory
else:
print(MESSAGE)
except Exception as e:
print(e)
2、打印图片分辨率def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] <
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] <
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
3、连接MySQL数据库import mysql.connector
# MySQl databses details
mydb = mysql.connector.connect(
host="0.0.0.0",
user="root",
passwd="",
database="db_name"
)
mycursor = mydb.cursor()
# Execute SQL Query =>>>> mycursor.execute("SQL Query")
mycursor.execute("SELECT column FROM table")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
4、PDF转音频import pyttsx3
import pyPDF2
book = open('book.pdf','rb')
pdfreader = pyPDF2.PdfFileReader(book)
pages = pdfreader.numPages
print(pages)
speaker = pyttsx3.init()
page= pdfreader.getpage(7)
text = page.extractText()
speaker.say(text)
speaker.runAndWait()