20個(gè)超實(shí)用Python自動(dòng)化腳本分享
在當(dāng)今的快節(jié)奏工作環(huán)境中,自動(dòng)化不再是一種奢侈,而是提高效率和精確性的必需手段。Python,以其易于學(xué)習(xí)和強(qiáng)大的功能而聞名,成為實(shí)現(xiàn)各種自動(dòng)化任務(wù)的理想選擇。無論是數(shù)據(jù)處理、報(bào)告生成,還是日常的文件管理,一個(gè)簡單但有效的Python腳本就能大幅減輕您的工作負(fù)擔(dān)。在本文中,我們將探索如何使用Python來創(chuàng)建多個(gè)自動(dòng)化腳本,它不僅能夠節(jié)省您的時(shí)間,還可以提高工作的準(zhǔn)確率和效率。我們先來看第一個(gè)自動(dòng)化腳本
自動(dòng)化文件管理
整理目錄中的文件
import os
from shutil import move
def sort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, filename)):
# 獲取文件擴(kuò)展名
file_extension = filename.split('.')[-1]
# 創(chuàng)建目標(biāo)目錄
destination_directory = os.path.join(directory_path, file_extension)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
# 移動(dòng)文件
move(os.path.join(directory_path, filename),
os.path.join(destination_directory, filename))
# 調(diào)用函數(shù),替換路徑
sort_files('your_directory_path')這段代碼包含一個(gè)名為sort_files的函數(shù),它接受一個(gè)目錄路徑作為參數(shù)。函數(shù)遍歷指定目錄中的所有文件,并檢查每個(gè)文件是否是一個(gè)常規(guī)文件(非目錄等)。對于每個(gè)文件,它提取出文件的擴(kuò)展名,創(chuàng)建一個(gè)以該擴(kuò)展名命名的新目錄(如果該目錄不存在的話),然后將文件移動(dòng)到新創(chuàng)建的對應(yīng)擴(kuò)展名的目錄中。
移除空白的文檔
import os
def remove_empty_folders(directory_path):
# 遍歷目錄樹
for root, dirs, files in os.walk(directory_path, topdown=False):
for folder in dirs:
folder_path = os.path.join(root, folder)
# 如果目錄為空,則刪除
if not os.listdir(folder_path):
os.rmdir(folder_path)
# 替換下面的路徑為自己想清理的目錄的路徑
remove_empty_folders('your_directory_path')這段代碼定義了一個(gè)名為remove_empty_folders的函數(shù),它接受一個(gè)目錄路徑作為參數(shù)。函數(shù)使用os.walk遍歷給定目錄及其所有子目錄。os.walk函數(shù)以topdown=False的方式執(zhí)行,這意味著遍歷將從目錄樹的最底層開始,確保在刪除空目錄之前已處理了所有子目錄。
對于每個(gè)找到的目錄,代碼檢查該目錄是否為空(即不包含任何文件或子目錄)。如果是空目錄,它就使用os.rmdir函數(shù)將其刪除。
多個(gè)文件的重命名
import os
def rename_files(directory_path, old_name, new_name):
# 遍歷目錄中的所有文件
for filename in os.listdir(directory_path):
# 檢查文件名中是否包含舊名稱
if old_name in filename:
# 生成新的文件名
new_filename = filename.replace(old_name, new_name)
# 重命名文件
os.rename(os.path.join(directory_path, filename),
os.path.join(directory_path, new_filename))
# 替換下面的路徑和名稱
# 例如 directory_path: 您要重命名文件的目錄路徑
rename_files('your_directory_path', 'old_name', 'new_name')這段代碼定義了一個(gè)名為rename_files的函數(shù),它接受三個(gè)參數(shù):要處理的目錄的路徑、需要被替換的舊名稱、以及新名稱。該函數(shù)遍歷指定目錄中的所有文件,檢查每個(gè)文件名是否包含舊名稱。如果包含,它會(huì)用str.replace方法生成一個(gè)新的文件名,然后使用os.rename方法將文件重命名。
Excel辦公自動(dòng)化軟件
讀取和寫入
import pandas as pd
def read_excel(file_path):
# 讀取Excel文件
df = pd.read_excel(file_path)
return df
def write_to_excel(data, file_path):
# 將數(shù)據(jù)寫入Excel文件
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)
# 讀取Excel文件
dataframe = read_excel('path_to_your_input_file.xlsx')
# 將修改后的數(shù)據(jù)寫入新的Excel文件
write_to_excel(dataframe, 'path_to_your_output_file.xlsx')我們主要是調(diào)用pandas模塊中的read_excel函數(shù)接受一個(gè)文件路徑作為參數(shù)并且讀取Excel文件,并將其作為DataFrame返回。write_to_excel函數(shù)則接受一個(gè)數(shù)據(jù)集和一個(gè)輸出文件路徑,將數(shù)據(jù)集轉(zhuǎn)換為DataFrame,然后使用to_excel方法寫入Excel文件。在to_excel方法中,index=False參數(shù)表示在輸出的Excel文件中不包括行索引。
合并多個(gè)工作表
import pandas as pd
def merge_sheets(file_path, output_file_path):
# 打開Excel文件
xls = pd.ExcelFile(file_path)
# 創(chuàng)建一個(gè)空的DataFrame
df = pd.DataFrame()
# 遍歷所有工作表
for sheet_name in xls.sheet_names:
# 讀取每個(gè)工作表
sheet_df = pd.read_excel(xls, sheet_name)
# 將每個(gè)工作表的數(shù)據(jù)追加到df中
df = df.append(sheet_df, ignore_index=True)
# 將合并后的數(shù)據(jù)寫入新的Excel文件
df.to_excel(output_file_path, index=False)
# 替換為自己的文件路徑
merge_sheets('path_to_your_excel_file.xlsx', 'path_to_your_output_file.xlsx')這段代碼定義了一個(gè)名為merge_sheets的函數(shù),它接受原始Excel文件的路徑和輸出文件的路徑作為參數(shù)。函數(shù)首先使用pd.ExcelFile讀取Excel文件,并創(chuàng)建一個(gè)空的DataFrame。然后,它遍歷該Excel文件中的所有工作表,使用pd.read_excel逐個(gè)讀取它們,并通過append方法將每個(gè)工作表的數(shù)據(jù)追加到之前創(chuàng)建的空DataFrame中。這里使用了ignore_index=True,意味著在合并數(shù)據(jù)時(shí)會(huì)重新生成索引。
最后,使用to_excel方法將合并后的數(shù)據(jù)保存到一個(gè)新的Excel文件中。在這個(gè)方法中,index=False參數(shù)表示在輸出文件中不包括行索引。
圖片處理
圖片的修剪
from PIL import Image
def resize_image(input_path, output_path, width, height):
# 打開圖片
image = Image.open(input_path)
# 調(diào)整圖片大小
resized_image = image.resize((width, height), Image.ANTIALIAS)
# 保存調(diào)整后的圖片
resized_image.save(output_path)
def crop_image(input_path, output_path, left, top, right, bottom):
# 打開圖片
image = Image.open(input_path)
# 裁剪圖片
cropped_image = image.crop((left, top, right, bottom))
# 保存裁剪后的圖片
cropped_image.save(output_path)
# 替換為自己的文件路徑和參數(shù)
resize_image('path_to_input_image.jpg', 'path_to_resized_image.jpg', 800, 600)
crop_image('path_to_input_image.jpg', 'path_to_cropped_image.jpg', 100, 100, 400, 400)在resize_image函數(shù)中,它接受輸入路徑、輸出路徑、以及新圖片的寬度和高度作為參數(shù)。該函數(shù)使用PIL庫打開圖片,然后調(diào)用resize方法將圖片大小調(diào)整為指定的寬度和高度。
crop_image函數(shù)接受輸入路徑、輸出路徑,以及裁剪區(qū)域的左、上、右、下四個(gè)坐標(biāo)作為參數(shù)。該函數(shù)同樣使用PIL庫打開圖片,然后使用crop方法根據(jù)提供的坐標(biāo)裁剪圖片。
添加水印
from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_path, output_path, watermark_text):
# 打開圖片
image = Image.open(input_path)
# 準(zhǔn)備繪制對象
draw = ImageDraw.Draw(image)
# 設(shè)置字體(這里使用Arial,大小為36)
font = ImageFont.truetype('arial.ttf', 36)
# 在圖片上添加水印文字
draw.text((10, 10), watermark_text, fill=(255, 255, 255, 128), font=font)
# 保存帶有水印的圖片
image.save(output_path)
# 替換為自己的文件路徑和水印文本
add_watermark('path_to_input_image.jpg', 'path_to_watermarked_image.jpg', 'Your Watermark Text')這段代碼定義了一個(gè)名為add_watermark的函數(shù),它接受輸入圖片的路徑、輸出圖片的路徑和水印文本作為參數(shù)。該函數(shù)首先使用PIL庫打開圖片,然后創(chuàng)建一個(gè)ImageDraw對象以便在圖片上繪制文本。接下來,設(shè)置字體(本例中使用Arial字體,字號為36),并使用draw.text方法將水印文本繪制到圖片上。最后,保存帶有水印的圖片到指定的輸出路徑。
創(chuàng)建縮略圖
from PIL import Image
def create_thumbnail(input_path, output_path, size=(128, 128)):
# 打開圖片
image = Image.open(input_path)
# 創(chuàng)建縮略圖
image.thumbnail(size)
# 保存縮略圖
image.save(output_path)
# 替換為自己的文件路徑
create_thumbnail('path_to_input_image.jpg', 'path_to_thumbnail_image.jpg')在這段代碼中,create_thumbnail函數(shù)接受三個(gè)參數(shù):輸入圖片的路徑、輸出圖片的路徑,以及縮略圖的尺寸(默認(rèn)為128x128像素)。函數(shù)使用PIL庫打開原始圖片,然后調(diào)用thumbnail方法來創(chuàng)建縮略圖。
系統(tǒng)任務(wù)
系統(tǒng)進(jìn)程管理
import psutil
def get_running_processes():
# 獲取當(dāng)前運(yùn)行的進(jìn)程信息
return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]
def kill_process_by_name(process_name):
# 遍歷當(dāng)前運(yùn)行的進(jìn)程
for p in psutil.process_iter(['pid', 'name', 'username']):
# 如果進(jìn)程名匹配,則終止進(jìn)程
if p.info['name'] == process_name:
p.kill()
# 獲取運(yùn)行中的進(jìn)程列表
running_processes = get_running_processes()
# 殺死指定名稱的進(jìn)程(請謹(jǐn)慎使用)
# kill_process_by_name('process_name_here')在get_running_processes函數(shù)中,使用psutil.process_iter方法來迭代當(dāng)前運(yùn)行的所有進(jìn)程,并獲取每個(gè)進(jìn)程的pid(進(jìn)程ID)、name(進(jìn)程名)和username(運(yùn)行該進(jìn)程的用戶)。這些信息被收集在一個(gè)列表中并返回。
kill_process_by_name函數(shù)也使用psutil.process_iter來遍歷所有進(jìn)程,但它檢查每個(gè)進(jìn)程的名稱是否與給定的process_name相匹配。如果找到匹配的進(jìn)程,它使用kill方法終止該進(jìn)程。
PDF文件操作
多個(gè)PDF文件合并
import PyPDF2
def merge_pdfs(input_paths, output_path):
# 創(chuàng)建PDF合并器對象
pdf_merger = PyPDF2.PdfMerger()
# 遍歷所有輸入路徑并添加到合并器
for path in input_paths:
with open(path, 'rb') as f:
pdf_merger.append(f)
# 將合并后的PDF寫入輸出文件
with open(output_path, 'wb') as f:
pdf_merger.write(f)
# 替換為自己的PDF文件路徑
input_pdf_paths = ['pdf1.pdf', 'pdf2.pdf', 'pdf3.pdf']
output_pdf_path = 'merged.pdf'
merge_pdfs(input_pdf_paths, output_pdf_path)在這個(gè)腳本中,merge_pdfs函數(shù)接受兩個(gè)參數(shù):一個(gè)包含要合并的PDF文件路徑的列表input_paths和一個(gè)輸出文件路徑output_path。函數(shù)首先創(chuàng)建了一個(gè)PyPDF2.PdfMerger對象,然后逐個(gè)打開輸入列表中的PDF文件,并使用append方法將它們添加到合并器中。最后,使用write方法將合并后的PDF輸出到指定的文件路徑。
PDF文件密碼保護(hù)
import PyPDF2
def add_password_protection(input_path, output_path, password):
# 打開要加密的PDF文件
with open(input_path, 'rb') as f:
pdf_reader = PyPDF2.PdfFileReader(f)
pdf_writer = PyPDF2.PdfFileWriter()
# 復(fù)制所有頁面到寫入器對象
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
# 為PDF文件設(shè)置密碼
pdf_writer.encrypt(password)
# 寫入加密后的PDF到輸出文件
with open(output_path, 'wb') as output_file:
pdf_writer.write(output_file)
# 請?zhí)鎿Q為自己的文件路徑和密碼
input_pdf_path = 'input.pdf'
output_pdf_path = 'protected.pdf'
password = 'your_password'
add_password_protection(input_pdf_path, output_pdf_path, password)在這段代碼中,add_password_protection函數(shù)接受輸入文件路徑input_path、輸出文件路徑output_path和密碼password作為參數(shù)。它首先打開輸入的PDF文件,使用PyPDF2.PdfFileReader讀取PDF內(nèi)容。然后,創(chuàng)建一個(gè)PyPDF2.PdfFileWriter對象,將從讀取器對象中獲取的所有頁面添加到寫入器對象中。使用encrypt方法為PDF設(shè)置密碼。最后,將加密后的PDF內(nèi)容寫入到輸出文件中。
以上就是20個(gè)超實(shí)用Python自動(dòng)化腳本分享的詳細(xì)內(nèi)容,更多關(guān)于Python自動(dòng)化腳本的資料請關(guān)注腳本之家其它相關(guān)文章!
- 分享10個(gè)拿來即用的Python自動(dòng)化腳本
- 10個(gè)殺手級應(yīng)用的Python自動(dòng)化腳本
- 5個(gè)Python殺手級的自動(dòng)化腳本分享
- 分享十個(gè)Python超級好用提高工作效率的自動(dòng)化腳本
- 分享4個(gè)Python中的非常好用的自動(dòng)化腳本
- 分享十個(gè)Python提高工作效率的自動(dòng)化腳本
- 八個(gè)超級好用的Python自動(dòng)化腳本(小結(jié))
- 十個(gè)簡單使用的Python自動(dòng)化腳本分享
- 分享5個(gè)方便好用的Python自動(dòng)化腳本
- 10個(gè)常用python自動(dòng)化腳本
相關(guān)文章
PyQt5?QLineEdit校驗(yàn)器限制輸入實(shí)例代碼
QLineEdit類是一個(gè)單行文本控件,可輸入單行字符串,可以設(shè)置回顯模式(Echomode)和掩碼模式,下面這篇文章主要給大家介紹了關(guān)于PyQt5?QLineEdit校驗(yàn)器限制輸入的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
Python中使用PyExecJS庫執(zhí)行JavaScript函數(shù)
Python在運(yùn)行JavaScript函數(shù)時(shí),需要用到外部庫來執(zhí)行JavaScript,本文主要介紹了Python中使用PyExecJS庫執(zhí)行JavaScript函數(shù),具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04
python3中替換python2中cmp函數(shù)的實(shí)現(xiàn)
這篇文章主要介紹了python3替換python2中cmp函數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
python3通過gevent.pool限制協(xié)程并發(fā)數(shù)量的實(shí)現(xiàn)方法
這篇文章主要介紹了python3通過gevent.pool限制協(xié)程并發(fā)數(shù)量的實(shí)現(xiàn)方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
Python設(shè)計(jì)模式之代理模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之代理模式,結(jié)合實(shí)例形式較為詳細(xì)的分析了代理模式的概念、原理及Python定義、使用代理模式相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
python os.path.isfile 的使用誤區(qū)詳解
今天小編就為大家分享一篇python os.path.isfile 的使用誤區(qū)詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

