Python script to sort files in a directory by their extension
import os
fromshutil import move
def sort_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)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))
复制代码
说明:
此Python脚本根据文件扩展名将文件分类到子目录中,以组织目录中的文件。它识别文件扩展名并将文件移动到适当的子目录。这对于整理下载文件夹或组织特定项目的文件很有用。
1.2 删除空文件夹
复制代码
Python script to remove empty folders in a directory
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)
复制代码
说明:
此Python脚本可以搜索并删除指定目录中的空文件夹。它可以帮助您在处理大量数据时保持文件夹结构的干净整洁。
1.3 重命名多个文件
复制代码
Python script to rename multiple files in a directory
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))
复制代码
说明:
此Python脚本允许您同时重命名目录中的多个文件。它将旧名称和新名称作为输入,并将所有符合指定条件的文件的旧名称替换为新名称。
2. 使用Python进行网页抓取
2.1从网站提取数据
复制代码
Python script for web scraping to extract data from a website
import requests
from bs4 import BeautifulSoup
def scrape_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
Your code here to extract relevant data from the website
复制代码
说明:
此Python脚本利用requests和BeautifulSoup库从网站上抓取数据。它获取网页内容并使用BeautifulSoup解析HTML。您可以自定义脚本来提取特定数据,例如标题、产品信息或价格。
2.2从网站提取数据
复制代码
Python script to download images in bulk from a website
import requests
def download_images(url, save_directory):
response = requests.get(url)
if response.status_code == 200:
images = response.json() # Assuming the API returns a JSON array of image URLs
for index, image_url in enumerate(images):
image_response = requests.get(image_url)
if image_response.status_code == 200:
with open(f"{savedirectory}/image{index}.jpg", "wb") as f:
f.write(image_response.content)
复制代码
说明:
此Python脚本旨在从网站批量下载图像。它为网站提供返回图像URL数组的JSON API。然后,该脚本循环访问URL并下载图像,并将其保存到指定目录。
2.3自动提交表单
复制代码
Python script to automate form submissions on a website
import requests
def submit_form(url, form_data):
response = requests.post(url, data=form_data)
if response.status_code == 200:
# Your code here to handle the response after form submission
复制代码
说明:
此Python脚本通过发送带有表单数据的POST请求来自动在网站上提交表单。您可以通过提供URL和要提交的必要表单数据来自定义脚本。
3. 文本处理和操作
3.1计算文本文件中的字数
复制代码
Python script to count words in a text file
def count_words(file_path):
with open(file_path, 'r') as f:
text = f.read()
word_count = len(text.split())
return word_count
复制代码
说明:
此Python脚本读取一个文本文件并计算它包含的单词数。它可用于快速分析文本文档的内容或跟踪写作项目中的字数情况。
3.2从网站提取数据
复制代码
Python script to find and replace text in a file
def find_replace(file_path, search_text, replace_text):
with open(file_path, 'r') as f:
text = f.read()
modified_text = text.replace(search_text, replace_text)
with open(file_path, 'w') as f:
f.write(modified_text)
复制代码
说明:
此Python脚本能搜索文件中的特定文本并将其替换为所需的文本。它对于批量替换某些短语或纠正大型文本文件中的错误很有帮助。
3.3生成随机文本
复制代码
Python script to generate random text
import random
import string
def generate_random_text(length):
letters = string.ascii_letters + string.digits + string.punctuation
random_text = ''.join(random.choice(letters) for i in range(length))
return random_text
复制代码
说明:
此Python脚本生成指定长度的随机文本。它可以用于测试和模拟,甚至可以作为创意写作的随机内容来源。
4.电子邮件自动化
4.1发送个性化电子邮件
复制代码
Python script to send personalized emails to a list of recipients
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_personalized_email(sender_email, sender_password, recipients, subject, body):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
for recipient_email in recipients:
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
复制代码
说明:
此Python脚本使您能够向收件人列表发送个性化电子邮件。您可以自定义发件人的电子邮件、密码、主题、正文和收件人电子邮件列表。请注意,出于安全原因,您在使用Gmail时应使用应用程序专用密码。
4.2通过电子邮件发送文件附件
复制代码
//代码效果参考:http://www.ningluan.com/sitemap/post.html
//代码效果参考:https://www.yopian.com/sitemap/post.html
//代码效果参考:http://www.92demo.com/sitemap/post.html
//代码效果参考:https://www.tvdy.cn/sitemap/post.html
Python script to send emails with file attachments
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender_email,sender_password, recipient_email, subject, body, file_path):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
with open(file_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {file_path}")
message.attach(part)
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()