赞
踩
Python是一种强大的编程语言,非常适合自动化各种任务。以下列出了Python常用于自动化的10个脚本示例,涵盖了文件管理、网络操作、数据处理等多个方面(文末附python学习资料)。
这个脚本可以定期备份指定目录下的所有文件到另一个位置。
import shutil
import os
import datetime
def backup_files(src, dst):
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
for filename in os.listdir(src):
shutil.copy(os.path.join(src, filename), os.path.join(dst, f"{timestamp}_{filename}"))
if __name__ == "__main__":
src_dir = "/path/to/source"
dst_dir = "/path/to/destination"
backup_files(src_dir, dst_dir)
该脚本可以从网页下载数据。
import requests
def download_file(url, path):
response = requests.get(url)
with open(path, 'wb') as file:
file.write(response.content)
if __name__ == "__main__":
url = "http://example.com/data.csv"
download_file(url, "/path/to/downloaded/file.csv")
批量重命名文件。
import os
def rename_files(directory, prefix="new_prefix"):
for filename in os.listdir(directory):
new_name = f"{prefix}_{filename}"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
if __name__ == "__main__":
directory = "/path/to/directory"
rename_files(directory)
读取CSV文件并进行一些基本的数据处理。
import csv
def process_csv(input_path, output_path):
with open(input_path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
fieldnames = reader.fieldnames + ['new_column']
with open(output_path, 'w', newline='') as outfile:
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
for row in reader:
row['new_column'] = row['column_name'] * 2
writer.writerow(row)
if __name__ == "__main__":
input_path = "/path/to/input.csv"
output_path = "/path/to/output.csv"
process_csv(input_path, output_path)
监控服务器的网络连接状态。
import subprocess
def check_network(host="8.8.8.8", port=53):
result = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True)
if result.returncode == 0:
print("Network is up.")
else:
print("Network is down.")
if __name__ == "__main__":
check_network()
自动发送电子邮件。
import smtplib
from email.mime.text import MIMEText
def send_email(subject, message, to_addr, from_addr, password):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr
server = smtplib.SMTP('smtp.example.com')
server.starttls()
server.login(from_addr, password)
server.send_message(msg)
server.quit()
if __name__ == "__main__":
subject = "Daily Report"
message = "This is the daily report."
to_addr = "recipient@example.com"
from_addr = "sender@example.com"
password = "password"
send_email(subject, message, to_addr, from_addr, password)
同步两个目录的内容。
import shutil
def sync_directories(src, dst):
shutil.rmtree(dst, ignore_errors=True)
shutil.copytree(src, dst)
if __name__ == "__main__":
src_dir = "/path/to/source"
dst_dir = "/path/to/destination"
sync_directories(src_dir, dst_dir)
抓取网页内容。
import requests
from bs4 import BeautifulSoup
def fetch_webpage(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.prettify()
if __name__ == "__main__":
url = "http://example.com"
webpage_content = fetch_webpage(url)
print(webpage_content)
分析日志文件中的特定模式。
import re
def analyze_logs(logfile, pattern):
with open(logfile, 'r') as file:
for line in file:
if re.search(pattern, line):
print(line.strip())
if __name__ == "__main__":
logfile = "/path/to/logfile.log"
pattern = r"ERROR"
analyze_logs(logfile, pattern)
使用定时器定期执行任务。
import time
def scheduled_task():
while True:
# Your task here
print("Executing task...")
time.sleep(3600) # Sleep for an hour
if __name__ == "__main__":
scheduled_task()
学会了Python就业还是不用愁的,这些行业在薪资待遇上可能会有一些区别,但是整体来看还是很好的,我也不会说往哪个方向发展是最好的,各取所长选择自己最感兴趣的去学习就好。
作为一个IT的过来人,我自己整理了一些python学习资料,希望对你们有帮助。
朋友们如果需要可以点击下方链接或微信扫描下方二维码都可以免费获取【保证100%免费】。
CSDN大礼包:《2024年最新Python全套学习资料包】免费领取(安全链接,放心点击)
编程资料、学习路线图、源代码、软件安装包等!
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习
因篇幅有限,仅展示部分图片
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。