python代码大全(持续更新)

  1. 读写文件
# 读取文件
with open('file.txt', 'r') as file:
    content = file.read()

# 写入文件
with open('file.txt', 'w') as file:
    file.write('Hello, World!')
  1. HTTP请求
import requests

response = requests.get('https://api.example.com/data')
data = response.json()
  1. JSON处理
import json

# JSON字符串转字典
data = json.loads('{"name": "John", "age": 30}')

# 字典转JSON字符串
json_string = json.dumps(data)
  1. 正则表达式
import re

text = "Find all matches in this text"
matches = re.findall(r'\bma\w+', text)
  1. 日期和时间
from datetime import datetime

# 当前时间
now = datetime.now()

# 格式化日期时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
  1. 随机数
import random

# 随机整数
rand_num = random.randint(1, 100)
  1. 列表推导式
# 从另一个列表创建新列表
squares = [x * x for x in range(10)]
  1. 函数定义
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
  1. 异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Divided by zero!")
    ```
10. 文件和目录操作
```python
import os

# 获取当前工作目录
cwd = os.getcwd()

# 列出目录内容
entries = os.listdir(cwd)
  1. 类和对象
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name}."

person = Person("John", 30)
print(person.greet())
  1. 网络编程
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("example.com", 80))
  1. 多线程
from threading import Thread

def print_numbers():
    for i in range(1, 6):
        print(i)

thread = Thread(target=print_numbers)
thread.start()
  1. 数据库操作
import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
  1. 网页爬虫
from bs4 import BeautifulSoup
import requests

response = requests.get('http://example.com')
soup = BeautifulSoup(response.content, 'html.parser')
titles = soup.find_all('h1')
  1. 使用List Comprehensions处理列表
# 获取列表中的偶数
even_numbers = [x for x in range(10) if x % 2 == 0]
  1. 文件夹遍历
import os

for root, dirs, files in os.walk('/path/to/folder'):
    for file in files:
        print(os.path.join(root, file))
  1. 使用字典(Maps)
# 创建和使用字典
capitals = {'USA': 'Washington D.C.', 'France': 'Paris', 'Italy': 'Rome'}
print(capitals['France'])
  1. Lambda表达式
# 使用lambda表达式进行排序
items = [{'name': 'John', 'age': 30}, {'name': 'Alice', 'age': 25}]
sorted_items = sorted(items, key=lambda x: x['age'])
  1. 文件操作
# 读取每行内容
with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())
  1. 生成器(Generators)
# 使用生成器产生斐波那契数列
def fib(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

for num in fib(10):
    print(num)
  1. 装饰器(Decorators)
def decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()
  1. 使用集合(Sets)
# 集合的创建和操作
a_set = {1, 2, 3}
a_set.add(4)
a_set.remove(2)
  1. 使用枚举(Enumerate)
# 枚举列表中的元素
for index, value in enumerate(['a', 'b', 'c']):
    print(f"{index}: {value}")
  1. 命令行参数解析
import argparse

parser = argparse.ArgumentParser(description='Example script.')
parser.add_argument('name', help='Your name')
args = parser.parse_args()

print(f"Hello, {args.name}")
  1. 环境变量读取
import os

# 读取环境变量
db_host = os.environ.get('DB_HOST', 'localhost')
  1. 创建简单的HTTP服务器
import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
  1. 使用Python进行数据分析
import pandas as pd

# 读取CSV文件
df = pd.read_csv('data.csv')

# 数据分析操作,例如计算平均值
print(df['column_name'].mean())
  1. 使用Matplotlib进行数据可视化
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 6]

plt.plot(x, y)
plt.show()
  1. 使用Pillow处理图像
from PIL import Image

# 打开图像
image = Image.open('image.jpg')

# 应用图像处理,例如旋转
image = image.rotate(90)

# 保存图像
image.save('rotated_image.jpg')

这些代码片段覆盖了Python编程中的常见场景和操作。

你可能感兴趣的:(python)