自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python增強辦公效率的 11 個實用代碼段

開發(fā)
本文將介紹一些實用的 Python 腳本,用于批量創(chuàng)建文件夾、重命名文件、處理 Excel 數(shù)據(jù)、合并 PDF 文件等。這些工具能顯著減少重復性工作,提升工作效率。

在日常工作中,許多任務(wù)可以通過編程自動化來提高效率。本文將介紹一些實用的 Python 腳本,用于批量創(chuàng)建文件夾、重命名文件、處理 Excel 數(shù)據(jù)、合并 PDF 文件等。這些工具能顯著減少重復性工作,提升工作效率。

1. 快速生成批量文件夾

工作中經(jīng)常需要創(chuàng)建多個文件夾來分類存儲不同類型的文件。手動創(chuàng)建不僅耗時還容易出錯。利用 Python 可以快速生成批量文件夾。

import os

def create_folders(base_path, folder_names):
    """
    在指定路徑下創(chuàng)建多個文件夾。
    
    :param base_path: 文件夾創(chuàng)建的基礎(chǔ)路徑
    :param folder_names: 要創(chuàng)建的文件夾名稱列表
    """
    for name in folder_names:
        path = os.path.join(base_path, name)
        if not os.path.exists(path):
            os.makedirs(path)
            print(f"創(chuàng)建文件夾 {path}")

# 示例使用
folder_names = ['2023年報表', '2023年會議記錄', '2023年項目文檔']
create_folders('C:\\Users\\YourName\\Documents', folder_names)

輸出結(jié)果:

創(chuàng)建文件夾 C:\Users\YourName\Documents\2023年報表
創(chuàng)建文件夾 C:\Users\YourName\Documents\2023年會議記錄
創(chuàng)建文件夾 C:\Users\YourName\Documents\2023年項目文檔

2. 批量重命名文件

當有大量文件需要重命名時,手動操作顯然不現(xiàn)實。Python 的 os 模塊可以輕松完成這一任務(wù)。

import os

def rename_files(directory, prefix):
    """
    批量重命名目錄下的所有文件,添加前綴。
    
    :param directory: 需要重命名文件所在的目錄
    :param prefix: 添加到文件名前面的前綴
    """
    for filename in os.listdir(directory):
        old_name = os.path.join(directory, filename)
        new_name = os.path.join(directory, f"{prefix}_{filename}")
        os.rename(old_name, new_name)
        print(f"重命名 {old_name} 為 {new_name}")

# 示例使用
rename_files('C:\\Users\\YourName\\Documents\\2023年報表', '報表')

輸出結(jié)果:

重命名 C:\Users\YourName\Documents\2023年報表\file1.xlsx 為 C:\Users\YourName\Documents\2023年報表\報表_file1.xlsx
重命名 C:\Users\YourName\Documents\2023年報表\file2.xlsx 為 C:\Users\YourName\Documents\2023年報表\報表_file2.xlsx

3. Excel 數(shù)據(jù)處理

日常工作中經(jīng)常需要處理 Excel 表格數(shù)據(jù)。使用 pandas 庫可以高效地讀取、處理 Excel 文件。

import pandas as pd

def process_excel(file_path):
    """
    讀取并處理 Excel 文件。
    
    :param file_path: Excel 文件路徑
    """
    # 讀取 Excel 文件
    df = pd.read_excel(file_path)
    
    # 處理數(shù)據(jù)
    df['Total'] = df['Quantity'] * df['Price']
    df.dropna(inplace=True)  # 刪除缺失值
    
    # 保存處理后的數(shù)據(jù)
    df.to_excel('processed_data.xlsx', index=False)

# 示例使用
process_excel('C:\\Users\\YourName\\Documents\\sales_data.xlsx')

輸出結(jié)果:

  • 原始 Excel 文件中的數(shù)據(jù)被讀入 DataFrame。
  • 新增一列 Total 計算銷售額。
  • 刪除包含 NaN 的行。
  • 將處理后的數(shù)據(jù)保存到新文件 processed_data.xlsx 中。

4. PDF 文檔合并

經(jīng)常需要將多個 PDF 文件合并成一個文檔。借助于 PyPDF2 庫可以輕松實現(xiàn)該功能。

from PyPDF2 import PdfFileMerger

def merge_pdfs(paths, output):
    """
    合并多個 PDF 文件。
    
    :param paths: PDF 文件路徑列表
    :param output: 輸出文件路徑
    """
    merger = PdfFileMerger()
    
    for pdf in paths:
        merger.append(pdf)
    
    merger.write(output)
    merger.close()

# 示例使用
pdf_paths = ['report_part1.pdf', 'report_part2.pdf', 'report_part3.pdf']
merge_pdfs(pdf_paths, 'complete_report.pdf')

輸出結(jié)果:

  • complete_report.pdf 文件中包含了三個部分的內(nèi)容。

5. 文本內(nèi)容替換

在處理大量文本文件時,經(jīng)常需要批量替換某些內(nèi)容。Python 的 re 模塊提供了強大的正則表達式支持,可以輕松完成這一任務(wù)。

import re
import os

def replace_text_in_files(directory, pattern, replacement):
    """
    在指定目錄下的所有文本文件中替換特定內(nèi)容。
    
    :param directory: 目錄路徑
    :param pattern: 要替換的模式(正則表達式)
    :param replacement: 替換的內(nèi)容
    """
    for filename in os.listdir(directory):
        if filename.endswith('.txt'):
            filepath = os.path.join(directory, filename)
            with open(filepath, 'r') as file:
                content = file.read()
            
            updated_content = re.sub(pattern, replacement, content)
            
            with open(filepath, 'w') as file:
                file.write(updated_content)
                print(f"更新文件 {filepath}")

# 示例使用
directory = 'C:\\Users\\YourName\\Documents\\text_files'
pattern = r'old_text'
replacement = 'new_text'
replace_text_in_files(directory, pattern, replacement)

輸出結(jié)果:

更新文件 C:\Users\YourName\Documents\text_files\file1.txt
更新文件 C:\Users\YourName\Documents\text_files\file2.txt

6. 發(fā)送郵件自動化

發(fā)送郵件是日常工作的一部分。使用 smtplib 和 email 庫可以自動發(fā)送郵件,節(jié)省時間和精力。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_emails):
    """
    發(fā)送郵件。
    
    :param subject: 郵件主題
    :param body: 郵件正文
    :param to_emails: 收件人郵箱列表
    """
    sender_email = 'your_email@example.com'
    sender_password = 'your_password'

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = ', '.join(to_emails)
    message['Subject'] = subject

    message.attach(MIMEText(body, 'plain'))

    try:
        server = smtplib.SMTP('smtp.example.com', 587)
        server.starttls()
        server.login(sender_email, sender_password)
        text = message.as_string()
        server.sendmail(sender_email, to_emails, text)
        server.quit()
        print("郵件發(fā)送成功")
    except Exception as e:
        print(f"郵件發(fā)送失?。簕e}")

# 示例使用
subject = "本周工作報告"
body = "這是本周的工作報告,請查收。"
to_emails = ['alice@example.com', 'bob@example.com']
send_email(subject, body, to_emails)

輸出結(jié)果:

郵件發(fā)送成功

7. 數(shù)據(jù)可視化

數(shù)據(jù)分析過程中,圖表能夠幫助更好地理解數(shù)據(jù)。使用 matplotlib 庫可以輕松繪制各種圖表。

import matplotlib.pyplot as plt
import pandas as pd

def plot_data(data, title, x_label, y_label):
    """
    繪制數(shù)據(jù)圖表。
    
    :param data: 數(shù)據(jù) DataFrame
    :param title: 圖表標題
    :param x_label: X 軸標簽
    :param y_label: Y 軸標簽
    """
    plt.figure(figsize=(10, 6))
    plt.plot(data[x_label], data[y_label])
    plt.title(title)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.grid(True)
    plt.show()

# 示例使用
data = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    'Sales': [200, 250, 300, 350, 400, 450]
})
plot_data(data, 'Monthly Sales', 'Month', 'Sales')

輸出結(jié)果:

  • 繪制了一個簡單的折線圖,顯示每月的銷售數(shù)據(jù)。

8. Excel 數(shù)據(jù)批量處理

當需要對多個 Excel 文件進行相同的操作時,可以編寫一個腳本來批量處理。

import pandas as pd
import os

def process_excel_files(directory):
    """
    批量處理目錄下的所有 Excel 文件。
    
    :param directory: 目錄路徑
    """
    for filename in os.listdir(directory):
        if filename.endswith('.xlsx'):
            filepath = os.path.join(directory, filename)
            df = pd.read_excel(filepath)
            
            # 數(shù)據(jù)處理
            df['Total'] = df['Quantity'] * df['Price']
            df.dropna(inplace=True)
            
            # 保存處理后的數(shù)據(jù)
            output_path = os.path.join(directory, f"processed_{filename}")
            df.to_excel(output_path, index=False)
            print(f"處理并保存文件 {output_path}")

# 示例使用
directory = 'C:\\Users\\YourName\\Documents\\sales_data'
process_excel_files(directory)

輸出結(jié)果:

處理并保存文件 C:\Users\YourName\Documents\sales_data\processed_sales1.xlsx
處理并保存文件 C:\Users\YourName\Documents\sales_data\processed_sales2.xlsx

9. 自動化生成報告

在定期匯報工作中,自動生成報告可以節(jié)省大量時間。使用 pandas 和 openpyxl 庫可以實現(xiàn)這一目標。

import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows

def generate_report(data, output_path):
    """
    生成 Excel 報告。
    
    :param data: 數(shù)據(jù) DataFrame
    :param output_path: 輸出文件路徑
    """
    wb = Workbook()
    ws = wb.active
    ws.title = 'Report'

    for r in dataframe_to_rows(data, index=False, header=True):
        ws.append(r)

    wb.save(output_path)
    print(f"報告已生成:{output_path}")

# 示例使用
data = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    'Sales': [200, 250, 300, 350, 400, 450]
})
generate_report(data, 'monthly_report.xlsx')

輸出結(jié)果:

報告已生成:monthly_report.xlsx

10. 文件壓縮與解壓

處理大量文件時,壓縮與解壓文件可以節(jié)省存儲空間。使用 zipfile 模塊可以輕松實現(xiàn)。

import zipfile
import os

def compress_files(directory, output_path):
    """
    壓縮指定目錄下的所有文件。
    
    :param directory: 目錄路徑
    :param output_path: 輸出文件路徑
    """
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(directory):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, directory))
                print(f"壓縮文件 {file_path}")

# 示例使用
directory = 'C:\\Users\\YourName\\Documents\\project_files'
output_path = 'project_files.zip'
compress_files(directory, output_path)

輸出結(jié)果:

壓縮文件 C:\Users\YourName\Documents\project_files\file1.txt
壓縮文件 C:\Users\YourName\Documents\project_files\file2.txt

11. 實戰(zhàn)案例:自動化數(shù)據(jù)處理與報告生成

假設(shè)你是一名財務(wù)分析師,每天需要處理大量的銷售數(shù)據(jù),并生成一份報告。以下是一個完整的自動化腳本示例:

import pandas as pd
import matplotlib.pyplot as plt
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import zipfile
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def process_data(input_directory, output_directory):
    """
    處理數(shù)據(jù)并生成報告。
    
    :param input_directory: 輸入數(shù)據(jù)目錄
    :param output_directory: 輸出數(shù)據(jù)目錄
    """
    # 讀取數(shù)據(jù)
    data = pd.DataFrame()
    for filename in os.listdir(input_directory):
        if filename.endswith('.xlsx'):
            filepath = os.path.join(input_directory, filename)
            df = pd.read_excel(filepath)
            data = pd.concat([data, df])

    # 數(shù)據(jù)處理
    data['Total'] = data['Quantity'] * data['Price']
    data.dropna(inplace=True)

    # 保存處理后的數(shù)據(jù)
    output_path = os.path.join(output_directory, 'processed_data.xlsx')
    data.to_excel(output_path, index=False)
    print(f"處理并保存數(shù)據(jù):{output_path}")

    # 生成圖表
    plt.figure(figsize=(10, 6))
    plt.plot(data['Date'], data['Total'])
    plt.title('Monthly Sales')
    plt.xlabel('Date')
    plt.ylabel('Total Sales')
    plt.grid(True)
    plt.savefig(os.path.join(output_directory, 'sales_chart.png'))
    print("圖表已生成")

    # 生成報告
    wb = Workbook()
    ws = wb.active
    ws.title = 'Report'

    for r in dataframe_to_rows(data, index=False, header=True):
        ws.append(r)

    wb.save(os.path.join(output_directory, 'monthly_report.xlsx'))
    print("報告已生成")

    # 壓縮文件
    with zipfile.ZipFile(os.path.join(output_directory, 'monthly_data.zip'), 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(output_directory):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, output_directory))
                print(f"壓縮文件 {file_path}")

    # 發(fā)送郵件
    sender_email = 'your_email@example.com'
    sender_password = 'your_password'
    to_emails = ['alice@example.com', 'bob@example.com']

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = ', '.join(to_emails)
    message['Subject'] = 'Monthly Report'

    with open(os.path.join(output_directory, 'monthly_report.xlsx'), 'rb') as file:
        attachment = file.read()
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment)
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename=monthly_report.xlsx')
        message.attach(part)

    with open(os.path.join(output_directory, 'sales_chart.png'), 'rb') as file:
        attachment = file.read()
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment)
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename=sales_chart.png')
        message.attach(part)

    try:
        server = smtplib.SMTP('smtp.example.com', 587)
        server.starttls()
        server.login(sender_email, sender_password)
        text = message.as_string()
        server.sendmail(sender_email, to_emails, text)
        server.quit()
        print("郵件發(fā)送成功")
    except Exception as e:
        print(f"郵件發(fā)送失?。簕e}")

# 示例使用
input_directory = 'C:\\Users\\YourName\\Documents\\sales_data'
output_directory = 'C:\\Users\\YourName\\Documents\\reports'
process_data(input_directory, output_directory)

輸出結(jié)果:

處理并保存數(shù)據(jù):C:\Users\YourName\Documents\reports\processed_data.xlsx
圖表已生成
報告已生成
壓縮文件 monthly_report.xlsx
壓縮文件 sales_chart.png
壓縮文件 processed_data.xlsx
郵件發(fā)送成功

總結(jié)

本文介紹了多種 Python 腳本,用于提高日常工作的效率。通過自動化批量創(chuàng)建文件夾、重命名文件、處理 Excel 數(shù)據(jù)、合并 PDF 文件、批量替換文本內(nèi)容、發(fā)送郵件、數(shù)據(jù)可視化、批量處理 Excel 文件、生成報告、壓縮文件等功能,可以顯著減少重復性工作。希望這些工具能幫助你更高效地完成工作任務(wù)。

責任編輯:趙寧寧 來源: 手把手PythonAI編程
相關(guān)推薦

2016-02-15 09:25:00

R語言運算效率大數(shù)據(jù)

2011-08-15 13:29:50

jQuery

2019-07-02 10:36:30

JavaScript硬件開發(fā)

2021-04-25 07:47:36

電腦軟件EverythingIDM

2020-01-03 10:24:06

Python 開發(fā)編程語言

2022-09-21 12:46:39

開發(fā)JavaScrip代碼

2024-09-26 06:21:59

Python代碼

2022-02-18 11:51:36

Python代碼編程語言

2024-10-28 19:36:05

2022-03-18 21:27:36

Python無代碼

2022-09-23 09:14:28

JavaScriptES6代碼

2024-11-26 14:18:44

Python代碼技巧

2022-06-23 09:04:14

ReactHooks項目

2025-03-03 00:15:00

JavaScript開發(fā)效率

2024-01-07 20:14:18

CSS開發(fā)工具

2023-11-22 13:33:22

VS Code人工智能插件

2022-01-16 08:00:28

PythonFor循環(huán)

2022-06-01 10:45:52

C語言代碼優(yōu)化

2013-12-16 10:27:16

2024-03-27 14:06:58

Python代碼開發(fā)
點贊
收藏

51CTO技術(shù)棧公眾號