Fundamentals 18 min read

50 Practical Python Code Examples Covering Files, Data Processing, Web Requests, Dates, and Utilities

This article presents 50 concise Python code snippets that demonstrate essential techniques for file and directory manipulation, data handling, web requests, date and time processing, and a variety of useful utilities, providing ready‑to‑use examples for developers of all levels.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
50 Practical Python Code Examples Covering Files, Data Processing, Web Requests, Dates, and Utilities

Python is a concise and powerful programming language that permeates many aspects of modern development. This article compiles 50 carefully selected Python code examples covering file and directory operations, data processing, web requests, date and time handling, and practical utilities.

1. File and Directory Operations

Basic file handling functions include reading a file, reading line by line, writing, appending, checking existence, creating directories, and deleting files or directories.

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

2. Data Processing and Analysis

Examples demonstrate counting elements with collections.Counter , removing duplicates while preserving order, merging dictionaries, and using list and dictionary comprehensions.

<code>from collections import Counter

def count_list_items(data_list):
    """统计列表中每个元素出现的次数,返回字典."""
    return Counter(data_list)
</code>
<code>def remove_duplicates_from_list(data_list):
    """去除列表中的重复元素,保持顺序."""
    return list(dict.fromkeys(data_list))
</code>

3. Network Requests and Web

Using the requests library, the article shows how to send GET and POST requests, download files, retrieve HTTP status codes, set timeouts, add custom headers, and handle cookies.

<code>import requests

def get_webpage_content(url):
    """发送 GET 请求到 URL 并返回网页内容."""
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        return f"请求失败: {e}"
</code>

4. Date and Time Handling

Functions illustrate obtaining the current datetime, formatting, parsing strings, calculating differences, extracting components, and converting timestamps.

<code>import datetime

def get_current_datetime():
    """获取当前日期和时间,返回 datetime 对象."""
    return datetime.datetime.now()
</code>
<code>def calculate_datetime_difference(datetime1, datetime2):
    """计算两个 datetime 对象的时间差,返回 timedelta 对象."""
    return datetime2 - datetime1
</code>

5. Practical Tools and Tricks

Additional utilities include generating random integers or floats, shuffling lists, measuring execution time, simple command‑line argument parsing, password generation, email sending, text replacement, and safe division with exception handling.

<code>import random

def generate_random_integer(start, end):
    """生成指定范围内的随机整数."""
    return random.randint(start, end)
</code>
<code>def safe_integer_division(numerator, denominator):
    """安全地进行整数除法,处理除零异常."""
    try:
        return numerator / denominator
    except ZeroDivisionError:
        return "除数不能为零"
    except TypeError:
        return "输入类型错误,请输入数字"
</code>

These 50 snippets provide ready‑to‑use building blocks that can accelerate everyday Python programming tasks.

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.