# Python script to sort files in a directory by their extensionimport os
from shutil import move
defsort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, filename)):
file_extension = filename.split('.')[-1]
destination_directory = os.path.join(directory_path, file_extension)
ifnot os.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))
# Python script to remove empty folders in a directoryimport os
defremove_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)
ifnot os.listdir(folder_path):
os.rmdir(folder_path)
说明:此脚本可以搜索并删除指定目录中的空文件夹,帮助保持文件夹结构的干净整洁。
1.3 重命名多个文件
# Python script to rename multiple files in a directoryimport os
defrename_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))
# Python script for web scraping to extract data from a websiteimport requests
from bs4 import BeautifulSoup
defscrape_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extract relevant data here, e.g., title
title = soup.find('title').get_text() if soup.find('title') else"No Title"print(f"Extracted Title: {title}")
# Python script to download images in bulk from a websiteimport requests
import os
defdownload_images(url, save_directory):
os.makedirs(save_directory, exist_ok=True)
response = requests.get(url)
if response.status_code == 200:
try:
images = response.json() # Assuming the API returns a JSON array of image URLsfor index, image_url inenumerate(images):
image_response = requests.get(image_url)
if image_response.status_code == 200:
withopen(f"{save_directory}/image_{index}.jpg", "wb") as f:
f.write(image_response.content)
except ValueError:
print("Response is not valid JSON")
# Python script to automate form submissions on a websiteimport requests
defsubmit_form(url, form_data):
response = requests.post(url, data=form_data)
if response.status_code == 200:
print("Form submitted successfully")
return response.text
else:
print(f"Failed to submit form: {response.status_code}")
说明:此脚本通过发送带有表单数据的 POST 请求来自动在网站上提交表单。您可以通过提供 URL 和要提交的必要表单数据来自定义脚本。
3. 文本处理和操作
3.1 计算文本文件中的字数
# Python script to count words in a text filedefcount_words(file_path):
withopen(file_path, 'r', encoding='utf-8') as f:
text = f.read()
word_count = len(text.split())
return word_count
# Python script to find and replace text in a filedeffind_replace(file_path, search_text, replace_text):
withopen(file_path, 'r', encoding='utf-8') as f:
text = f.read()
modified_text = text.replace(search_text, replace_text)
withopen(file_path, 'w', encoding='utf-8') as f:
f.write(modified_text)
# Python script to read and write data to an Excel spreadsheetimport pandas as pd
defread_excel(file_path):
df = pd.read_excel(file_path)
return df
defwrite_to_excel(data, file_path):
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)
# Python script for data analysis and visualization with pandas and matplotlibimport pandas as pd
import matplotlib.pyplot as plt
defanalyze_and_visualize_data(data):
df = pd.DataFrame(data)
# Example visualization
df.plot(kind='bar')
plt.show()
# Python script to connect to a database and execute queriesimport sqlite3
defconnect_to_database(database_path):
connection = sqlite3.connect(database_path)
return connection
defexecute_query(connection, query):
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
说明:此脚本允许您连接到 SQLite 数据库并执行查询。您可以使用适当的 Python 数据库驱动程序将其调整为与其他数据库管理系统(例如 MySQL 或 PostgreSQL)配合使用。
6.2 执行 SQL 查询
# Python script to execute SQL queries on a databaseimport sqlite3
defexecute_query(connection, query):
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
# Python script to automatically share content on social media platformsimport random
defget_random_content():
contents = ["Check out this update!", "New article published.", "Happy coding!"]
return random.choice(contents)
defpost_random_content_to_twitter(api_key, api_secret, access_token, access_token_secret):
content = get_random_content()
# Call post_to_twitter function hereprint(f"Posting to Twitter: {content}")
defpost_random_content_to_facebook(api_key, api_secret, access_token):
content = get_random_content()
# Call post_to_facebook function hereprint(f"Posting to Facebook: {content}")
# Python script for scraping data from social media platformsimport requests
defscrape_social_media_data(url):
response = requests.get(url)
# Use BeautifulSoup or similar to parse responsereturn response.text
说明:此脚本执行网页抓取以从社交媒体平台提取数据。它获取所提供 URL 的内容,然后使用 BeautifulSoup 等技术来解析 HTML 并提取所需的数据。
8. 自动化系统任务
8.1 管理系统进程
# Python script to manage system processesimport psutil
defget_running_processes():
return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]
defkill_process_by_name(process_name):
for p in psutil.process_iter(['pid', 'name', 'username']):
if p.info['name'] == process_name:
p.kill()
# Python script to monitor disk space and send an alert if it's lowimport psutil
defcheck_disk_space(minimum_threshold_gb):
disk = psutil.disk_usage('/')
free_space_gb = disk.free / (1024**3) # Convert bytes to GBif free_space_gb < minimum_threshold_gb:
print("Warning: Low disk space!")
# Python script to check the status of a websiteimport requests
defcheck_website_status(url):
response = requests.get(url)
if response.status_code == 200:
print(f"Website {url} is up")
else:
print(f"Website {url} returned status code {response.status_code}")
说明:此脚本通过向提供的 URL 发送 HTTP GET 请求来检查网站的状态。它可以帮助您监控网站及其响应代码的可用性。
10.2 自动 FTP 传输
# Python script to automate FTP file transfersfrom ftplib import FTP
defftp_file_transfer(host, username, password, local_file_path, remote_file_path):
with FTP(host) as ftp:
ftp.login(user=username, passwd=password)
withopen(local_file_path, 'rb') as f:
ftp.storbinary(f'STOR {remote_file_path}', f)
# Python script to extract text from PDFsimport PyPDF2
defextract_text_from_pdf(file_path):
withopen(file_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
text = ''for page_num inrange(pdf_reader.num_pages):
page = pdf_reader.get_page(page_num)
text += page.extract_text()
return text
说明:此脚本使用 PyPDF2 库从 PDF 文件中提取文本。它读取 PDF 的每一页并将提取的文本编译为单个字符串。
12.2 合并多个 PDF
# Python script to merge multiple PDFs into a single PDFimport PyPDF2
defmerge_pdfs(input_paths, output_path):
pdf_merger = PyPDF2.PdfMerger()
for path in input_paths:
withopen(path, 'rb') as f:
pdf_merger.append(f)
withopen(output_path, 'wb') as f:
pdf_merger.write(f)
说明:此脚本将多个 PDF 文件合并为一个 PDF 文档。它可以方便地将单独的 PDF、演示文稿或其他文档合并为一个统一的文件。
12.3 添加密码保护
# Python script to add password protection to a PDFimport PyPDF2
defadd_password_protection(input_path, output_path, password):
withopen(input_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
pdf_writer = PyPDF2.PdfWriter()
for page_num inrange(pdf_reader.num_pages):
page = pdf_reader.get_page(page_num)
pdf_writer.add_page(page)
pdf_writer.encrypt(password)
withopen(output_path, 'wb') as output_file:
pdf_writer.write(output_file)
说明:此脚本为 PDF 文件添加密码保护。它使用密码对 PDF 进行加密,确保只有拥有正确密码的人才能访问内容。
13. 自动化 GUI
13.1 自动化鼠标和键盘
# Python script for GUI automation using pyautoguiimport pyautogui
defautomate_gui():
# Simulate mouse movement and click
pyautogui.moveTo(100, 100, duration=1)
pyautogui.click()
# Python script for unit testing with the unittest moduleimport unittest
defadd(a, b):
return a + b
classTestAddFunction(unittest.TestCase):
deftest_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
deftest_add_negative_numbers(self):
self.assertEqual(add(-2, -3), -5)
deftest_add_zero(self):
self.assertEqual(add(5, 0), 5)
if __name__ == '__main__':
unittest.main()
# Python script for web testing using Seleniumfrom selenium import webdriver
defperform_web_test():
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# Interact with web elements here
driver.quit()
说明:此脚本使用 Selenium 库来自动化 Web 测试。它启动 Web 浏览器,导航到指定的 URL,并与 Web 元素交互以测试网页的功能。
14.3 测试自动化框架
# Python script for building test automation frameworks# Define framework architecture and tools heredefsetup_framework():
print("Setting up test environment...")
returnTrue
# Python script to automate uploading files to cloud storage# Requires boto3 for AWS S3 or google-cloud-storage for GCSdefupload_to_cloud(bucket_name, file_path):
# Implementation depends on specific cloud provider SDKprint(f"Uploading {file_path} to {bucket_name}")
说明:此脚本使用 Boto3 库与 Amazon Web Services (AWS) 交互并创建 EC2 实例。它可以扩展以执行各种任务,例如创建 S3 buckets、管理 IAM 角色或启动 Lambda 函数。
15.3 自动化 Google 云端硬盘
# Python script to automate interactions with Google Drive# Requires google-api-python-clientdefinteract_with_drive():
# Connect to Google Drive APIprint("Connecting to Google Drive...")
说明:以编程方式与 Google Drive 交互可以简化文件管理和组织。该脚本可以充当一个利用 Google Drive API 将 Google Drive 功能集成到 Python 脚本中的起点。
16. 财务自动化
16.1 分析股票价格
# Python script for stock price analysis# Requires yfinance or similardefanalyze_stock_price(symbol):
# Fetch data using APIprint(f"Analyzing stock: {symbol}")
说明:自动化获取和分析股票价格数据的过程对投资者和金融分析师来说是十分有益的。该脚本可作为一个使用金融 API 将股票市场数据集成到 Python 脚本中的起点。
16.2 货币汇率
# Python script to fetch currency exchange rates# Requires fixer.io or openexchangerates APIdefget_exchange_rates():
# Fetch rates from APIprint("Fetching exchange rates...")
说明:此脚本利用货币兑换 API 来获取和显示不同货币之间的汇率。它可用于财务规划、国际贸易或旅行相关的应用程序。
16.3 预算追踪
# Python script for budget tracking and analysisimport pandas as pd
deftrack_budget(file_path):
df = pd.read_csv(file_path)
total_income = df[df['type'] == 'income']['amount'].sum()
total_expense = df[df['type'] == 'expense']['amount'].sum()
print(f"Income: {total_income}, Expense: {total_expense}")
# Python script for sentiment analysis using NLTK or other NLP librariesimport nltk
from nltk.sentiment import SentimentIntensityAnalyzer
defanalyze_sentiment(text):
nltk.download('vader_lexicon')
sia = SentimentIntensityAnalyzer()
sentiment_score = sia.polarity_scores(text)
return sentiment_score
# Python script for language translation using NLP libraries# Requires googletrans or deep_translatordeftranslate_text(text, target_lang):
# Connect to translation APIprint(f"Translating to {target_lang}")
说明:自动化语言翻译可以促进跨越语言障碍的沟通。该脚本可适配连接各种翻译 API 并支持多语言通信。