Fundamentals 31 min read

50 Practical Python Code Snippets for File Operations, Data Processing, Web Requests, Date/Time Handling, and Utilities

This article presents fifty ready‑to‑use Python examples covering file and directory manipulation, data processing, network requests, date‑time utilities, and assorted handy tools, each accompanied by clear explanations and complete code snippets to help developers quickly apply common programming tasks.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
50 Practical Python Code Snippets for File Operations, Data Processing, Web Requests, Date/Time Handling, and Utilities

Python is a concise and powerful language that permeates many areas of software development. This collection gathers 50 carefully selected Python code snippets covering file handling, data manipulation, web requests, date‑time processing, and useful utilities.

1. File and Directory Operations

File and directory operations are fundamental; Python provides robust libraries for these tasks.

Case 1: Read file content

def read_file_content(filepath):
    """读取文件内容并返回字符串."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "文件未找到"

# 示例
file_content = read_file_content('example.txt')
print(file_content)

Case 2: Read file line by line

def read_file_line_by_line(filepath):
    """逐行读取文件内容并返回列表."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        return lines
    except FileNotFoundError:
        return ["文件未找到"]

# 示例
lines = read_file_line_by_line('example.txt')
for line in lines:
    print(line.strip())  # strip()去除行尾的换行符

Case 3: Write content to file

def write_content_to_file(filepath, content):
    """将内容写入文件."""
    try:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        return "写入成功"
    except Exception as e:
        return f"写入失败: {e}"

# 示例
write_result = write_content_to_file('output.txt', '这是要写入的内容。\n第二行内容。')
print(write_result)

Case 4: Append content to file

def append_content_to_file(filepath, content):
    """将内容追加到文件末尾."""
    try:
        with open(filepath, 'a', encoding='utf-8') as f:
            f.write(content)
        return "追加成功"
    except Exception as e:
        return f"追加失败: {e}"

# 示例
append_result = append_content_to_file('output.txt', '\n这是追加的内容。')
print(append_result)

Case 5: Check if file exists

import os

def check_file_exists(filepath):
    """检查文件是否存在."""
    return os.path.exists(filepath)

# 示例
exists = check_file_exists('example.txt')
print(f"文件是否存在: {exists}")

Case 6: Create directory

import os

def create_directory(dirpath):
    """创建目录."""
    try:
        os.makedirs(dirpath, exist_ok=True)
        return f"目录 '{dirpath}' 创建成功"
    except Exception as e:
        return f"目录创建失败: {e}"

# 示例
create_result = create_directory('new_directory')
print(create_result)

Case 7: Delete file

import os

def delete_file(filepath):
    """删除文件."""
    try:
        os.remove(filepath)
        return f"文件 '{filepath}' 删除成功"
    except FileNotFoundError:
        return "文件未找到"
    except Exception as e:
        return f"文件删除失败: {e}"

# 示例
delete_result = delete_file('output.txt')
print(delete_result)

Case 8: Delete empty directory

import os

def delete_directory(dirpath):
    """删除目录 (目录必须为空)."""
    try:
        os.rmdir(dirpath)
        return f"目录 '{dirpath}' 删除成功"
    except FileNotFoundError:
        return "目录未找到"
    except OSError:
        return "目录非空,无法删除"
    except Exception as e:
        return f"目录删除失败: {e}"

# 示例
delete_result = delete_directory('new_directory')
print(delete_result)  # 如果目录不为空,会打印 "目录非空,无法删除"

Case 9: List directory contents

import os

def list_directory_contents(dirpath):
    """列出目录中的文件和子目录."""
    try:
        contents = os.listdir(dirpath)
        return contents
    except FileNotFoundError:
        return ["目录未找到"]

# 示例
directory_contents = list_directory_contents('.')  # '.' 表示当前目录
print(f"目录内容: {directory_contents}")

Case 10: Get file size

import os

def get_file_size(filepath):
    """获取文件大小,单位为字节."""
    try:
        size_in_bytes = os.path.getsize(filepath)
        return size_in_bytes
    except FileNotFoundError:
        return "文件未找到"

# 示例
file_size = get_file_size('example.txt')
print(f"文件大小: {file_size} 字节")

2. Data Processing and Analysis

Python’s standard library (collections, itertools) and popular packages (pandas, numpy) provide powerful data‑handling capabilities.

Case 11: Count occurrences in a list

from collections import Counter

def count_list_items(data_list):
    """统计列表中每个元素出现的次数,返回字典."""
    return Counter(data_list)

# 示例
my_list = ['a', 'b', 'a', 'c', 'b', 'b']
counts = count_list_items(my_list)
print(f"元素计数: {counts}")  # Counter({'b': 3, 'a': 2, 'c': 1})

Case 12: Remove duplicates while preserving order

def remove_duplicates_from_list(data_list):
    """去除列表中的重复元素,保持顺序."""
    return list(dict.fromkeys(data_list))

# 示例
my_list = [1, 2, 2, 3, 4, 4, 5, 1]
unique_list = remove_duplicates_from_list(my_list)
print(f"去重后的列表: {unique_list}")  # [1, 2, 3, 4, 5]

Case 13: Merge two dictionaries

def merge_dictionaries(dict1, dict2):
    """合并两个字典,如果键冲突,dict2 的值覆盖 dict1 的."""
    merged_dict = dict1.copy()  # 创建 dict1 的副本,避免修改原字典
    merged_dict.update(dict2)   # 将 dict2 的键值对添加到 merged_dict
    return merged_dict

# 示例
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = merge_dictionaries(dict1, dict2)
print(f"合并后的字典: {merged}")  # {'a': 1, 'b': 3, 'c': 4}

Case 14: Reverse dictionary key‑value pairs

def reverse_dictionary(data_dict):
    """反转字典的键值对."""
    return {v: k for k, v in data_dict.items()}

# 示例
my_dict = {'name': 'Alice', 'age': 30}
reversed_dict = reverse_dictionary(my_dict)
print(f"反转后的字典: {reversed_dict}")  # {'Alice': 'name', 30: 'age'}

Case 15: Sort dictionary by value

def sort_dictionary_by_value(data_dict, reverse=False):
    """按字典的值排序,返回排序后的键值对列表."""
    return sorted(data_dict.items(), key=lambda item: item[1], reverse=reverse)

# 示例
my_dict = {'a': 10, 'c': 1, 'b': 5}
sorted_dict = sort_dictionary_by_value(my_dict)
print(f"按值升序排序: {sorted_dict}")  # [('c', 1), ('b', 5), ('a', 10)]
sorted_dict_desc = sort_dictionary_by_value(my_dict, reverse=True)
print(f"按值降序排序: {sorted_dict_desc}")  # [('a', 10), ('b', 5), ('c', 1)]

Case 16: List comprehension – generate squares

def generate_squares(n):
    """使用列表推导式生成 0 到 n-1 的平方列表."""
    return [x**2 for x in range(n)]

# 示例
squares = generate_squares(5)
print(f"平方列表: {squares}")  # [0, 1, 4, 9, 16]

Case 17: Dictionary comprehension – generate squares

def generate_dict_squares(n):
    """使用字典推导式生成 0 到 n-1 的平方字典,键为数字,值为平方."""
    return {x: x**2 for x in range(n)}

# 示例
dict_squares = generate_dict_squares(5)
print(f"平方字典: {dict_squares}")  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Case 18: Use zip to iterate multiple lists

def combine_lists(names, ages, cities):
    """使用 zip 函数同时迭代三个列表,返回姓名、年龄和城市的组合列表."""
    combined_list = []
    for name, age, city in zip(names, ages, cities):
        combined_list.append(f"{name} is {age} years old and lives in {city}")
    return combined_list

# 示例
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 28]
cities = ['New York', 'London', 'Paris']
combined = combine_lists(names, ages, cities)
for item in combined:
    print(item)

Case 19: Use enumerate to get index while iterating

def list_with_index(data_list):
    """使用 enumerate 函数迭代列表,返回元素和索引的组合列表."""
    indexed_list = []
    for index, item in enumerate(data_list):
        indexed_list.append(f"Index {index}: {item}")
    return indexed_list

# 示例
my_list = ['apple', 'banana', 'cherry']
indexed = list_with_index(my_list)
for item in indexed:
    print(item)

Case 20: Group data with itertools.groupby

import itertools

def group_by_key(data_list, key_func):
    """使用 itertools.groupby 函数根据 key_func 分组数据."""
    sorted_data = sorted(data_list, key=key_func)  # groupby 前需要先排序
    grouped_data = {}
    for key, group in itertools.groupby(sorted_data, key=key_func):
        grouped_data[key] = list(group)  # group 是迭代器,需要转换为 list
    return grouped_data

# 示例
data = [
    {'city': 'London', 'name': 'Alice'},
    {'city': 'Paris', 'name': 'Bob'},
    {'city': 'London', 'name': 'Charlie'},
    {'city': 'Paris', 'name': 'David'}
]

grouped_by_city = group_by_key(data, key_func=lambda x: x['city'])
print(f"按城市分组: {grouped_by_city}")

3. Network Requests and Web

The requests library makes HTTP interactions straightforward.

Case 21: Send GET request

import requests

def get_webpage_content(url):
    """发送 GET 请求到 URL 并返回网页内容."""
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功 (状态码 200)
        return response.text
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"

# 示例
webpage_content = get_webpage_content('https://www.example.com')
print(webpage_content[:200])  # 打印前 200 个字符

Case 22: Send POST request with JSON data

import requests, json

def post_data_to_url(url, data):
    """发送 POST 请求到 URL 并传递 JSON 数据."""
    try:
        headers = {'Content-Type': 'application/json'}
        response = requests.post(url, data=json.dumps(data), headers=headers)
        response.raise_for_status()
        return response.json()  # 尝试解析 JSON 响应
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"
    except json.JSONDecodeError:
        return "响应不是有效的 JSON 格式"

# 示例
post_url = 'https://httpbin.org/post'  # 用于测试 HTTP 请求的网站
post_data = {'name': 'John', 'age': 30}
post_response = post_data_to_url(post_url, post_data)
print(f"POST 响应: {post_response}")

Case 23: Download file

import requests

def download_file(url, filepath):
    """从 URL 下载文件并保存到本地."""
    try:
        response = requests.get(url, stream=True)  # stream=True 用于大文件下载
        response.raise_for_status()
        with open(filepath, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):  # 分块写入,避免内存溢出
                f.write(chunk)
        return f"文件下载成功,保存到: {filepath}"
    except requests.exceptions.RequestException as e:
        return f"文件下载失败: {e}"

# 示例
file_url = 'https://www.easygifanimator.net/images/samples/video-to-gif-sample.gif'  # 一个 GIF 示例
download_result = download_file(file_url, 'sample.gif')
print(download_result)

Case 24: Get HTTP status code (HEAD request)

import requests

def get_http_status_code(url):
    """获取 URL 的 HTTP 状态码."""
    try:
        response = requests.head(url)  # 使用 HEAD 请求,只获取头部信息,更高效
        return response.status_code
    except requests.exceptions.RequestException:
        return "请求失败"

# 示例
status_code = get_http_status_code('https://www.example.com')
print(f"HTTP 状态码: {status_code}")  # 通常为 200

Case 25: Set request timeout

import requests

def get_webpage_with_timeout(url, timeout_seconds):
    """发送 GET 请求,并设置超时时间."""
    try:
        response = requests.get(url, timeout=timeout_seconds)
        response.raise_for_status()
        return response.text
    except requests.exceptions.Timeout:
        return "请求超时"
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"

# 示例
content_with_timeout = get_webpage_with_timeout('https://www.example.com', 5)  # 超时时间为 5 秒
print(content_with_timeout[:200])

Case 26: Add custom headers

import requests

def get_webpage_with_headers(url, headers):
    """发送 GET 请求,并添加自定义请求头."""
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"

# 示例
custom_headers = {'User-Agent': 'My-Custom-User-Agent/1.0'}
content_with_headers = get_webpage_with_headers('https://www.example.com', custom_headers)
print(content_with_headers[:200])

Case 27: Retrieve cookies from response

import requests

def get_cookies_from_url(url):
    """获取 URL 返回的 cookies."""
    try:
        response = requests.get(url)
        return response.cookies.get_dict()  # 将 Cookies 对象转换为字典
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"

# 示例
cookies = get_cookies_from_url('https://www.example.com')
print(f"Cookies: {cookies}")

Case 28: Send request with cookies

import requests

def get_webpage_with_cookies(url, cookies_dict):
    """发送 GET 请求,并附带 cookies."""
    try:
        response = requests.get(url, cookies=cookies_dict)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"

# 示例
cookies_to_send = {'session_id': '1234567890'}  # 假设的 cookies
content_with_cookies = get_webpage_with_cookies('https://www.example.com', cookies_to_send)
print(content_with_cookies[:200])

Case 29: Simple URL encoding

import urllib.parse

def url_encode_string(string_to_encode):
    """对字符串进行 URL 编码."""
    return urllib.parse.quote(string_to_encode)

# 示例
encoded_string = url_encode_string("search query with spaces")
print(f"URL 编码后的字符串: {encoded_string}")  # search%20query%20with%20spaces

Case 30: Simple URL decoding

import urllib.parse

def url_decode_string(encoded_string):
    """对 URL 编码的字符串进行解码."""
    return urllib.parse.unquote(encoded_string)

# 示例
decoded_string = url_decode_string("search%20query%20with%20spaces")
print(f"URL 解码后的字符串: {decoded_string}")  # search query with spaces

4. Date and Time Handling

Python’s datetime module offers rich date‑time functionality.

Case 31: Get current date and time

import datetime

def get_current_datetime():
    """获取当前日期和时间,返回 datetime 对象."""
    return datetime.datetime.now()

# 示例
current_datetime = get_current_datetime()
print(f"当前日期时间: {current_datetime}")

Case 32: Format datetime

import datetime

def format_datetime(datetime_obj, format_string="%Y-%m-%d %H:%M:%S"):
    """将 datetime 对象格式化为字符串."""
    return datetime_obj.strftime(format_string)

# 示例
now = datetime.datetime.now()
formatted_datetime = format_datetime(now)
print(f"格式化后的日期时间: {formatted_datetime}")  # 例如: 2023-10-27 10:30:45

Case 33: Parse datetime string

import datetime

def parse_datetime_string(datetime_string, format_string="%Y-%m-%d %H:%M:%S"):
    """将字符串解析为 datetime 对象."""
    try:
        return datetime.datetime.strptime(datetime_string, format_string)
    except ValueError:
        return "日期时间字符串格式错误"

# 示例
date_string = "2023-10-27 10:30:00"
parsed_datetime = parse_datetime_string(date_string)
print(f"解析后的 datetime 对象: {parsed_datetime}")

Case 34: Calculate datetime difference

import datetime

def calculate_datetime_difference(datetime1, datetime2):
    """计算两个 datetime 对象的时间差,返回 timedelta 对象."""
    return datetime2 - datetime1

# 示例
datetime1 = datetime.datetime(2023, 10, 26)
datetime2 = datetime.datetime(2023, 10, 27)
time_difference = calculate_datetime_difference(datetime1, datetime2)
print(f"时间差: {time_difference}")  # 1 day, 0:00:00

Case 35: Get year, month, day from a datetime

import datetime

def get_date_components(datetime_obj):
    """获取 datetime 对象的年份、月份、日."""
    return {'year': datetime_obj.year, 'month': datetime_obj.month, 'day': datetime_obj.day}

# 示例
now = datetime.datetime.now()
date_components = get_date_components(now)
print(f"日期组件: {date_components}")  # {'year': 2023, 'month': 10, 'day': 27}

Case 36: Get hour, minute, second

import datetime

def get_time_components(datetime_obj):
    """获取 datetime 对象的小时、分钟、秒."""
    return {'hour': datetime_obj.hour, 'minute': datetime_obj.minute, 'second': datetime_obj.second}

# 示例
now = datetime.datetime.now()
time_components = get_time_components(now)
print(f"时间组件: {time_components}")  # {'hour': 10, 'minute': 45, 'second': 30}

Case 37: Get current timestamp (seconds)

import time

def get_current_timestamp():
    """获取当前时间戳 (秒)."""
    return time.time()

# 示例
timestamp = get_current_timestamp()
print(f"当前时间戳: {timestamp}")  # 例如: 1698384000.0

Case 38: Convert timestamp to datetime

import datetime, time

def timestamp_to_datetime(timestamp):
    """将时间戳转换为 datetime 对象."""
    return datetime.datetime.fromtimestamp(timestamp)

# 示例
timestamp_value = time.time()
datetime_from_timestamp = timestamp_to_datetime(timestamp_value)
print(f"时间戳转换为 datetime 对象: {datetime_from_timestamp}")

Case 39: First and last day of a month

import datetime, calendar

def get_month_first_last_day(year, month):
    """获取某年某月的第一天和最后一天."""
    first_day = datetime.date(year, month, 1)
    last_day = datetime.date(year, month, calendar.monthrange(year, month)[1])
    return {'first_day': first_day, 'last_day': last_day}

# 示例
month_days = get_month_first_last_day(2023, 10)
print(f"2023年10月的第一天和最后一天: {month_days}")  # {'first_day': datetime.date(2023, 10, 1), 'last_day': datetime.date(2023, 10, 31)}

Case 40: Add or subtract days

import datetime

def add_days_to_date(date_obj, days_to_add):
    """给日期增加指定天数."""
    delta = datetime.timedelta(days=days_to_add)
    return date_obj + delta

def subtract_days_from_date(date_obj, days_to_subtract):
    """给日期减少指定天数."""
    delta = datetime.timedelta(days=days_to_subtract)
    return date_obj - delta

# 示例
today = datetime.date.today()
future_date = add_days_to_date(today, 7)  # 7 天后
past_date = subtract_days_from_date(today, 3)  # 3 天前
print(f"7 天后: {future_date}, 3 天前: {past_date}")

5. Practical Tools and Tricks

Finally, a collection of handy utilities.

Case 41: Generate random integer

import random

def generate_random_integer(start, end):
    """生成指定范围内的随机整数."""
    return random.randint(start, end)

# 示例
random_number = generate_random_integer(1, 100)
print(f"随机整数 (1-100): {random_number}")

Case 42: Generate random float

import random

def generate_random_float(start, end):
    """生成指定范围内的随机浮点数."""
    return random.uniform(start, end)

# 示例
random_float = generate_random_float(0, 1)
print(f"随机浮点数 (0-1): {random_float}")

Case 43: Choose random item from list

import random

def choose_random_item_from_list(data_list):
    """从列表中随机选择一个元素."""
    if not data_list:
        return "列表为空"
    return random.choice(data_list)

# 示例
my_list = ['apple', 'banana', 'cherry']
random_item = choose_random_item_from_list(my_list)
print(f"随机选择的元素: {random_item}")

Case 44: Shuffle list

import random

def shuffle_list(data_list):
    """打乱列表顺序 (原地修改)."""
    random.shuffle(data_list)
    return data_list

# 示例
my_list = [1, 2, 3, 4, 5]
shuffled_list = shuffle_list(my_list.copy())  # 避免修改原列表
print(f"打乱后的列表: {shuffled_list}")

Case 45: Measure execution time of a function

import time

def calculate_execution_time(func, *args, **kwargs):
    """计算函数运行时间 (秒)."""
    start_time = time.time()
    result = func(*args, **kwargs)
    end_time = time.time()
    execution_time = end_time - start_time
    return execution_time, result  # 返回运行时间和函数结果

# 示例函数 (计算平方和)
def sum_of_squares(n):
    return sum([i**2 for i in range(n)])

execution_time, result = calculate_execution_time(sum_of_squares, 100000)
print(f"函数运行时间: {execution_time:.4f} 秒, 结果: {result}")

Case 46: Simple command‑line argument parsing

import argparse

def parse_command_line_arguments():
    """使用 argparse 解析命令行参数."""
    parser = argparse.ArgumentParser(description="一个简单的命令行工具")
    parser.add_argument("filename", help="要处理的文件名")
    parser.add_argument("-n", "--number", type=int, help="一个数字参数", default=10)
    args = parser.parse_args()
    return args

# 示例 (在命令行中运行: python your_script_name.py input.txt -n 20)
# args = parse_command_line_arguments()
# print(f"文件名: {args.filename}, 数字参数: {args.number}")

Case 47: Simple password generator

import random, string

def generate_password(length=12):
    """生成指定长度的随机密码,包含字母和数字."""
    characters = string.ascii_letters + string.digits
    password = ''.join(random.choice(characters) for i in range(length))
    return password

# 示例
password = generate_password(16)
print(f"随机密码: {password}")

Case 48: Simple email sender (requires SMTP configuration)

import smtplib
from email.mime.text import MIMEText

def send_email(sender_email, sender_password, receiver_email, subject, message, smtp_server='smtp.example.com', smtp_port=587):
    """发送邮件 (需要配置SMTP服务器)."""
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = sender_email
    msg['To'] = receiver_email
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()  # 启用 TLS 加密
        server.login(sender_email, sender_password)  # 登录邮箱
        server.sendmail(sender_email, [receiver_email], msg.as_string())
        server.quit()
        return "邮件发送成功"
    except Exception as e:
        return f"邮件发送失败: {e}"

# 示例 (请替换为您的邮箱信息)
# sender = "[email protected]"
# password = "your_email_password"
# receiver = "[email protected]"
# email_result = send_email(sender, password, receiver, "测试邮件", "这是一封测试邮件。")
# print(email_result)

Case 49: Simple text replacement

def replace_text_in_string(text, old_substring, new_substring):
    """在字符串中替换子字符串."""
    return text.replace(old_substring, new_substring)

# 示例
original_text = "Hello World! World is great."
replaced_text = replace_text_in_string(original_text, "World", "Python")
print(f"替换后的文本: {replaced_text}")  # Hello Python! Python is great.

Case 50: Safe integer division with exception handling

def safe_integer_division(numerator, denominator):
    """安全地进行整数除法,处理除零异常."""
    try:
        result = numerator / denominator
        return result
    except ZeroDivisionError:
        return "除数不能为零"
    except TypeError:
        return "输入类型错误,请输入数字"

# 示例
division_result1 = safe_integer_division(10, 2)
division_result2 = safe_integer_division(10, 0)
division_result3 = safe_integer_division(10, 'a')
print(f"10 / 2 = {division_result1}")  # 5.0
print(f"10 / 0 = {division_result2}")  # 除数不能为零
print(f"10 / 'a' = {division_result3}")  # 输入类型错误,请输入数字

These fifty Python snippets illustrate common tasks and serve as a quick reference for developers seeking practical, ready‑to‑use solutions.

PythonData ProcessingDateTimecode examplesfile handlingutilitiesweb requests
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.