
你有没有这样的体验?
每天下班前的1小时,都在做重复又耗时的工作?
整理文件、处理数据、发送邮件... 这些工作不复杂,但特别耗费时间。
明明这些都可以自动完成,为什么我们还要花大量时间做重复的事?
我曾经也每天花2小时做这些琐事,直到我发现了Python自动化的魅力。
今天,我就来分享30个职场必备的Python自动化脚本,帮助你把宝贵的时间用在更重要的事情上。
往期Python阅读>>
Python 自动化做数据可视化10个示例(含代码),强烈推荐
你是不是觉得Python很难学?
别担心,这些脚本都是我精心挑选的实用脚本,很多都是复制粘贴就能用的。
自动化:让程序代替人,完成重复、耗时的任务。简单来说,就是用代码解决日常问题。
你不需要懂太多Python语法,只需要根据自己的需求修改一下配置参数,就能实现自动化。

从网上下载的CSV文件总是有很多重复数据和格式问题?
这个脚本可以帮你自动清洗CSV文件,让数据更干净易处理。
import csvdef clean_csv(input_file, output_file): with open(input_file, mode='r', newline='', encoding='utf-8') as infile, \ open(output_file, mode='w', newline='', encoding='utf-8') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) for row in reader: cleaned_row = [cell.strip() for cell in row] writer.writerow(cleaned_row)input_file = '/path/to/input.csv'output_file = '/path/to/cleaned_output.csv'clean_csv(input_file, output_file)想知道一个文件夹里有多少文件和子文件夹?
这个脚本可以帮你快速统计文件夹的详细信息。
import osdef count_files_and_dirs(directory): total_files = 0 total_dirs = 0 for root, dirs, files in os.walk(directory): total_files += len(files) total_dirs += len(dirs) return total_files, total_dirsdirectory = '/path/to/your/directory'files, dirs = count_files_and_dirs(directory)print(f"Total files: {files}, Total directories: {dirs}")想了解文件夹里都有哪些类型的文件?
这个脚本可以按文件扩展名统计文件数量。
import osdef classify_files_by_type(directory): file_types = {} for filename in os.listdir(directory): if os.path.isfile(os.path.join(directory, filename)): extension = os.path.splitext(filename)[1] if extension in file_types: file_types[extension] += 1 else: file_types[extension] = 1 return file_typesdirectory = '/path/to/your/directory'file_types = classify_files_by_type(directory)for ext, count in file_types.items(): print(f"Files with extension '{ext}': {count}")需要从图片中提取文字?
这个脚本可以帮你使用OCR技术从图片中识别文字内容。
from PIL import Imagefrom pytesseract import pytesseractdef image_to_text(image_path): img = Image.open(image_path) text = pytesseract.image_to_string(img) return textimage_path = '/path/to/your/image.png'text = image_to_text(image_path)print(f"Text from image: {text}")需要从视频中提取音频?
这个脚本可以帮你快速将视频文件转换为MP3音频格式。
from moviepy.editor import VideoFileClipdef convert_video_to_audio(video_path, audio_path): clip = VideoFileClip(video_path) clip.audio.write_audiofile(audio_path)video_path = '/path/to/your/video.mp4'audio_path = '/path/to/converted/audio.mp3'convert_video_to_audio(video_path, audio_path)想批量下载网页上的所有图片?
这个脚本可以帮你自动抓取网页中的所有图片并保存到本地。
import requestsfrom bs4 import BeautifulSoupimport osdef extract_images_from_webpage(url, output_dir): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') images = soup.find_all('img') os.makedirs(output_dir, exist_ok=True) for image in images: src = image.get('src') if src and src.startswith('http'): image_data = requests.get(src).content filename = os.path.join(output_dir, os.path.basename(src)) with open(filename, 'wb') as f: f.write(image_data)url = 'https://example.com'output_dir = '/path/to/output/images'extract_images_from_webpage(url, output_dir)需要翻译大量文档?
这个脚本可以帮你自动翻译文本文件。
from deep_translator import GoogleTranslatordef translate_text(input_file, output_file, target_language): with open(input_file, 'r', encoding='utf-8') as file: text = file.read() translated_text = GoogleTranslator(source='auto', target=target_language).translate(text) with open(output_file, 'w', encoding='utf-8') as file: file.write(translated_text)input_file = '/path/to/your/text.txt'output_file = '/path/to/translated_text.txt'target_language = 'es'translate_text(input_file, output_file, target_language)长篇文章读不完?
这个脚本可以帮你自动生成文章摘要,快速了解核心内容。
from transformers import pipelinedef generate_summary(text): summarizer = pipeline("summarization") summary = summarizer(text, max_length=130, min_length=30, do_sample=False) return summary[0]['summary_text']text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor."""summary = generate_summary(text)print(f"Summary: {summary}")需要在多个文件夹之间同步内容?
这个脚本可以帮你将源文件夹的内容同步到目标文件夹。
import shutilimport osdef sync_folders(src_folder, dst_folder): for item in os.listdir(src_folder): s = os.path.join(src_folder, item) d = os.path.join(dst_folder, item) if os.path.isdir(s): shutil.copytree(s, d, dirs_exist_ok=True) else: shutil.copy2(s, d)src_folder = '/path/to/source/folder'dst_folder = '/path/to/destination/folder'sync_folders(src_folder, dst_folder)需要将数据备份到云存储?
这个脚本可以帮你将文件自动上传到AWS S3等云存储服务。
import boto3def upload_to_s3(bucket_name, local_file_path, remote_file_path): s3 = boto3.client('s3') s3.upload_file(local_file_path, bucket_name, remote_file_path)bucket_name = 'your-bucket-name'local_file_path = '/path/to/your/local/file'remote_file_path = 'path/to/remote/file'upload_to_s3(bucket_name, local_file_path, remote_file_path)每天都在处理一堆文件,文件名杂乱无章?
这个脚本可以帮你批量重命名文件,统一添加项目前缀。
import osdef batch_rename(directory, prefix): for i, filename in enumerate(os.listdir(directory)): os.rename( os.path.join(directory, filename), os.path.join(directory, f"{prefix}_{i}{os.path.splitext(filename)[1]}") )directory = '/path/to/files'prefix = 'new_name'batch_rename(directory, prefix)
需要每周定时发送周报?
这个脚本可以帮你自动发送邮件。
import smtplibfrom email.mime.text import MIMETextdef send_email(subject, body, to_email): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = 'your_email@example.com' msg['To'] = to_email with smtplib.SMTP('smtp.example.com', 587) as server: server.starttls() server.login('your_email@example.com', 'your_password') server.send_message(msg)send_email('Test Subject', 'This is the email body', 'recipient@example.com')需要监控某个网页是否有更新?
这个脚本可以帮你实时监控网页内容变化。
import requestsimport timedef monitor_website(url, check_interval=60): previous_content = requests.get(url).text while True: time.sleep(check_interval) current_content = requests.get(url).text if current_content != previous_content: print("Website content has changed!") previous_content = current_contentmonitor_website('https://example.com')需要填写大量表单?
这个脚本可以帮你自动填写网页表单。
from selenium import webdriverdef auto_fill_form(url, form_data): driver = webdriver.Chrome() driver.get(url) for field_name, value in form_data.items(): element = driver.find_element_by_name(field_name) element.send_keys(value) submit_button = driver.find_element_by_xpath("//input[@type='submit']") submit_button.click()form_data = { 'username': 'your_username', 'password': 'your_password'}auto_fill_form('https://example.com/login', form_data)需要定期生成Word报告?
这个脚本可以帮你自动生成格式化的Word文档。
from docx import Documentdef generate_report(title, content, output_file): doc = Document() doc.add_heading(title, level=1) doc.add_paragraph(content) doc.save(output_file)generate_report('Monthly Report', 'This is report content...', 'monthly_report.docx')需要在Twitter上自动发布内容?
这个脚本可以帮你自动发布推文。
import tweepydef tweet_message(api_key, api_secret, access_token, access_token_secret, message): auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) api.update_status(message)tweet_message('your_api_key', 'your_api_secret', 'your_access_token', 'your_access_token_secret', 'Hello from Python!')需要把会议录音转换成文字记录?
这个脚本可以帮你使用语音识别技术自动转写会议录音。
import speech_recognition as srdef transcribe_meeting(audio_file): r = sr.Recognizer() with sr.AudioFile(audio_file) as source: audio = r.record(source) try: return r.recognize_google(audio) except Exception as e: return f"Error: {str(e)}"transcription = transcribe_meeting('meeting_recording.wav')with open('meeting_transcript.txt', 'w') as f: f.write(transcription)数据都准备好了,但是需要花时间做图表?
这个脚本可以自动从数据文件生成可视化图表。
import pandas as pdimport matplotlib.pyplot as pltdef auto_visualize(data_file): df = pd.read_csv(data_file) df.plot(kind='bar') plt.savefig('visualization.png')auto_visualize('data.csv')担心密码不安全?
这个脚本可以帮你加密和管理密码。
from cryptography.fernet import Fernetimport jsondef generate_key(): return Fernet.generate_key()def encrypt_password(key, password): f = Fernet(key) return f.encrypt(password.encode()).decode()def decrypt_password(key, encrypted_password): f = Fernet(key) return f.decrypt(encrypted_password.encode()).decode()key = generate_key()encrypted = encrypt_password(key, "my_secret_password")print(decrypt_password(key, encrypted))需要实时监控系统资源使用情况?
这个脚本可以帮你监控CPU和内存使用率。
import psutilimport timedef monitor_resources(interval=5): while True: cpu = psutil.cpu_percent() memory = psutil.virtual_memory().percent print(f"CPU Usage: {cpu}%, Memory Usage: {memory}%") time.sleep(interval)monitor_resources()需要给文件添加统一前缀?
这个脚本可以批量重命名文件夹中的所有文件。
import osdef rename_files(directory, prefix): for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isfile(file_path): new_filename = f"{prefix}_{filename}" new_file_path = os.path.join(directory, new_filename) os.rename(file_path, new_file_path) print(f"Renamed '{filename}' to '{new_filename}'")# 示例用法rename_files('/path/to/your/files', 'project')下载文件夹总是乱糟糟的?
这个脚本可以自动将文件按类型分类到不同子文件夹。
import osimport shutildef organize_folder(folder_path): file_types = { "Images": [".jpg", ".jpeg", ".png", ".gif"], "Documents": [".pdf", ".docx", ".txt"], "Spreadsheets": [".xlsx", ".csv"], "Videos": [".mp4", ".mov", ".avi"] } for file_name in os.listdir(folder_path): file_path = os.path.join(folder_path, file_name) if os.path.isfile(file_path): file_ext = os.path.splitext(file_name)[1].lower() for folder, extensions in file_types.items(): if file_ext in extensions: target_folder = os.path.join(folder_path, folder) os.makedirs(target_folder, exist_ok=True) shutil.move(file_path, os.path.join(target_folder, file_name)) break需要定期备份重要文件?
这个脚本将指定文件夹压缩备份,并添加时间戳。
import osimport shutilimport datetimeimport zipfiledef backup_files(src_dir, backup_dir): current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") backup_name = f"backup_{current_time}" backup_path = os.path.join(backup_dir, backup_name) if not os.path.exists(backup_dir): os.makedirs(backup_dir) with zipfile.ZipFile(backup_path + '.zip', 'w', zipfile.ZIP_DEFLATED) as zipf: for root, _, files in os.walk(src_dir): for file in files: file_path = os.path.join(root, file) arc_name = os.path.relpath(file_path, src_dir) zipf.write(file_path, arc_name) print(f"备份完成!文件保存在: {backup_path}.zip")需要发送带附件的邮件?
这个脚本可以自动发送带附件的邮件。
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextdef send_email(subject, body, recipient): sender_email = "your_email@gmail.com" sender_password = "your_password" message = MIMEMultipart() message["From"] = sender_email message["To"] = recipient message["Subject"] = subject message.attach(MIMEText(body, "plain")) with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls() server.login(sender_email, sender_password) server.send_message(message) print("Email sent!")需要获取网页上的新闻头条?
这个脚本可以抓取网页头条新闻,保持信息更新。
import requestsfrom bs4 import BeautifulSoupdef fetch_headlines(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') headlines = soup.find_all('h2') for i, headline in enumerate(headlines[:5]): print(f"{i+1}. {headline.text.strip()}")# 示例用法fetch_headlines("https://news.ycombinator.com/")每天都要打开同样的网页?
这个脚本可以一键打开工作所需的所有网页。
import webbrowserdef open_websites(): urls = [ "https://mail.google.com", "https://www.jira.com", "https://www.github.com" ] for url in urls: webbrowser.open(url)# 示例用法open_websites()需要批量替换文本文件中的内容?
这个脚本可以批量替换文本文件中的内容。
def replace_text_in_file(file_path, old_text, new_text): with open(file_path, 'r+') as file: content = file.read() new_content = content.replace(old_text, new_text) file.seek(0) file.write(new_content) file.truncate()# 示例用法replace_text_in_file('/your/text.txt', 'old_word', 'new_word')需要实时监控文件夹变化并自动备份?
这个脚本可以实时监控文件夹变化并自动备份重要文件。
import osimport shutilfrom watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandlerfrom datetime import datetimeclass FileBackupHandler(FileSystemEventHandler): def __init__(self, source_dir, backup_dir): self.source_dir = source_dir self.backup_dir = backup_dir def on_modified(self, event): if not event.is_directory: self.copy_file(event.src_path) def copy_file(self, src): timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") backup_path = os.path.join(self.backup_dir, f"backup_{timestamp}") os.makedirs(backup_path, exist_ok=True) shutil.copy2(src, backup_path)def monitor_folder(source_dir, backup_dir): event_handler = FileBackupHandler(source_dir, backup_dir) observer = Observer() observer.schedule(event_handler, source_dir, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()需要灵活安排定时任务?
这个脚本可以灵活安排定时任务,如每日报表生成、定期数据备份等。
import scheduleimport timedef job(): print("Job running...")# 设置定时任务schedule.every(1).minutes.do(job)schedule.every().day.at("10:30").do(job)while True: schedule.run_pending() time.sleep(1)需要在Twitter上自动发布内容?
这个脚本可以自动发布社交媒体内容,适用于品牌营销和内容运营。
import tweepydef post_tweet(api_key, api_secret, access_token, access_secret, message): auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) api.update_status(message)# 示例用法post_tweet("API_KEY", "API_SECRET", "ACCESS_TOKEN", "ACCESS_SECRET", "Hello, Twitter!")看完这些脚本,你是不是觉得Python自动化其实没那么难?
第一步:选择合适的脚本。根据你的工作需求,选择上面的脚本。
第二步:修改配置参数。把脚本中的路径和配置改成你自己的。
第三步:运行脚本。保存为Python文件,点击运行按钮。
你可能觉得,学习Python要花很多时间,但是相比之下,我们每天花在重复性工作上的时间更多。
时间成本:如果每天花1小时在重复性工作上,一年就是365小时,也就是46个工作日。
通过学习Python自动化,你可以把这些时间省下来,用来做更有价值的事情。
1. 从简单的开始
先从文件处理类的脚本开始,比如批量重命名、文件分类等,这些脚本修改参数就能用,容易上手。
2. 记录日常重复性工作
在工作中,把你觉得浪费时间的事情记录下来,然后搜索对应的Python解决方案,慢慢积累自己的自动化工具箱。
3. 养成自动化思维
遇到新的任务,先思考:这个任务可以用自动化完成吗?然后再动手做。
这些脚本虽然看起来很简单,但它们能带来的变化是巨大的。
你不用再担心下班前的文件整理工作,不用再担心错过某个定时任务,也不用再为复制粘贴数据而烦恼。
更重要的是,你可以把节省下来的时间用在更有创造性的工作上,提升自己的价值。
我曾经也是一个每天花2小时做重复性工作的人,但Python自动化帮我把这些时间都省了下来。
现在,我可以把更多时间用在思考问题和解决问题上,效率提升了不止10倍。
自动化不是为了替代人,而是为了让人有更多时间去做更有价值的事情。
希望今天分享的30个脚本能帮助你节省时间,提升效率。
💬 你日常工作中最想自动化的任务是什么?评论区聊聊~
如果对你有帮助,点个在看让更多人看到吧 👇
想高效学习Python?下面三本精选好书满足你的不同需求!
《流畅的Python(第2版)》——Python进阶必读!深入讲解高级特性与最佳实践,适合想精进的开发者。
《Python从新手到高手》:初学者首选,系统学习全栈技能。
《Python数据分析:从零基础入门到案例实战》——数据科学利器!手把手教你用Python处理数据,实战案例学完就能用。
三本书均支持先用后付、运费险和7天无理由退货,放心购买!点击“购买”按钮,立即开启你的Python学习之旅吧!
https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c
