基本文件读写
with open('file.txt",'w') as f:f.write('Hello, World!')with open('file.txt','r') as f:content = f.read()
路径处理
import osfrom pathlib import Pathfile_path = os.path.join('folder', "file.txt")path = Path('folder')/ 'file.txt' #现代写法
压缩/解压缩文件
Import zipfilewith zipfile.ZipFile('archive.zip','w')as zipf: zipf.write('file.txt')with zipfile.ZipFile('archive.zip','r') as zipf: zipf.extractall('extracted')
列表推导式
squares =[x**2 for x in range(10)]even_squares =[x**2 for x in range(10)if x % 2 == 0]
字典操作
person ={'name':'Alice','age': 30}name = person.get('name','未知') #安全获取for key,value in person.items(): print(f"{key}: {value}")
集合操作
a={1,2,3,4}b={3,4,5,6}Print(a.union(b)) #并集:{1,2,3,4,5,6}print(a.intersection(b)) #交集:{3,4}
字符串格式化
name,age ="Alice",30print(f"{name}今年{age}岁") # f-stringprint("{0}今年{1}岁".format(name, age))
正则表达式
import retext ="联系方式:email@example.com 电话 123-4567"emails=re.findall(r'[\w._%+-]+@[\w.-]+\.[a-zA-Z]{2,}',text)phones=re.findall(r'\d{3}-\d{4}',text)
Base64编码
Import base64encoded = base64.b64encode("Hello".encode())decoded = base64.b64decode(encoded).decode()
装饰器
import timedef timer(func): def wrapper(*args,**kwargs): start = time.time() result = func(*args, **kwargs) print(f"耗时:{time.time()- start}秒") return result return wrapper Lambda 表达式 add = lambda x,y:x + y Sorted_items=sorted(items, key=lambda x:x[1])
参数解包
def add(a,b, c): return a + b + cvalues =[1,2,3]print(add(*values)) # 解包列表params = {'a':1,'b':2,'c':3}print(add(**params)) #解包字典
获取和格式化当前时间
from datetime import datetime, timedeltanow = datetime.now()formatted = now.strftime("%Y-%m-%d%H:%M:%S" )print(f"当前时间:{formatted}")
日期计算
tomorrow = now + timedelta(days=1)Last_week = now - timedelta(weeks=1)time diff = tomorrow - now #计算时间差
解析日期字符串
Date_str ="2023-01-15"date obj = datetime.strptime(date_str, "%Y-%m-%d" )
JSON处理
Import jsondata ={'name':'Alice','age': 30}json_str = json.dumps(data,indent=2) #转为JSONparsed = json.loads(json_str) #解析JSON
CSV处理
import csvwith open('data.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows([['Name','Age'],['Alice',25]])with open('data.csv','r')as f: reader = csv.reader(f) for row in reader: print(row)
XML处理
import xml.etree.ElementTree as ETXml_str ='<root><itemid="1">值</item></root>'root = ET.fromstring(xml str)value = root.find('item').text
发送HTTP请求
import requestsresponse = requests.get('https://api.example.com/data')if response.status_code == 200:data = response.json()
解析网页
from bs4 import BeautifulSouphtml = requests.get('https://example.com').textsoup = BeautifulSoup(html, 'html.parser')title = soup.title.textlinks = soup.find _all('a')
URL解析与构建
from urllib.parse import urlparse, urlencodeParsed_url= urlparse("https://example.com/path")params = {''name": ''张三'',"age": 30}query = urlencode(params)
异常处理
try: result=10/0 #会引发 ZeroDivisionErrorexcept ZeroDivisionError as e: print(f"捕获到错误:{e}")except Exception as e print(f捕获其他错误:{e}")finally: print("始终执行的代码")
日志记录
import logginglogging.basicconfig( level=logging.INFO, format='%(asctime)s-%(levelname)s-%(message)s', filename='app.log')logging.info('程序启动')logging.warning('警告信息')logging.error('错误信息')
多线程
import threadingdef task(name): print(f"线程{name}运行中")threads = [threading.Thread(target=task, args=(i,)) for i in range(3)]for t in threads: t.start()
异步编程
import asyncioasync def say_hello(delay, name): a wait asyncio.sleep(delay) print(f"Hello, {name}")async def main(): await asyncio.gather( say_hello(1, "Alice") say_hello(2, "Bob" ) }# asyncio.run(main()) # Python 3.7+
连接和创建表
import sqlite3#连接数据库conn = sqlite3.connect('example.db' )cursor = conn.cursor()# 创建表cursor.execute('''CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
数据库操作
# 插入数据cursor.execute("INSERT INTO users VALUES(?,?,?)", (1,'Alice',25))conn.commit()#查询数据cursor.execute("SELECT * FROM users WHERE age > ?",(20,))for row in cursor.fetchall(): print(row)conn.close()
基本类定义
class Person:def _init_(self, name, age): self.name = name self.age = agedef greet(self): return f“你好,我是{self.name}"
属性装饰器
class Temperature:def _init_(self, celsius): self. celsius = celsius@propertydef celsius(self): return self.celsius@propertydef fahrenheit(self): return self._celsius* 9/5 + 32
魔术方法
class Vector: def _init_(self,x,y): self.x,self.y=x,y def _add_(self, other): return Vector(self.x+ other.x, self.y + other.y) def _str_(self): return f"Vector({self.x},{self.y})"
生成器函数
def fibonacci(n): a,b=0,1 for i in range(n): yield a a,b = b,a + b
生成器表达式
squares =(x**2 for xin range(10)) # 比列表推导省内存
迭代工具
from itertools import cycle,chain, islicecolors = cycle(['红','绿','蓝']) # 无限循环print(next(colors),next(colors)) #红 绿combined=chain([1,2],[3,4]) #连接多个可迭代对象first_5=islice(fibonacci(100),5) # 切片迭代器
创建DataFrame
import pandas as pdimport numpy as npdata = {'Name': ['Alice','Bob', 'charlie'],'Age':[25,30,35],'City':['北京','上海','广州’]}df = pd.DataFrame(data)
数据选择与过滤
names = df['Name'] #选择单列subset = df[['Name', 'Age']] # 选择多列young = df[df['Age']< 30] #条件过滤
数据分析
print(df.describe()) #统计摘要grouped = df.groupby('City').mean() # 分组统计
基本图像操作
from PIL import Image, ImageFilter, ImageDrawimg = Image.open('example.jpg')print(f"大小:{img.size},格式:{img.format}")
图像处理
resized = img.resize((300,200))rotated = img.rotate(45)blurred = img.filter(ImageFilter.BLUR)cropped = img.crop((100,100,400,400)) #(left,top,right,bottom)
绘图与保存
draw = ImageDraw.Draw(img)draw.rectangle((50,50,150,150),outline="red")draw.text((10,10),"Hello", fill="white" )# 保存图像img.save('modified.jpg', quality=95)
环境变量操作
import osfrom dotenv import load_dotenvload_dotenv() # 加载.env文件api_key = os.getenv('API KEY','默认值')os.environ['DEBUG']= 'True' #设置环境变量
命令行参数
import argparseparser = argparse.ArgumentParser(description='示例程序')parser.addargument('filename',help='输入文件')parser.add argument('--v','--verbose', action='store true')args = parser.parse_args()
子进程管理
import subprocessresultresult = subprocess.run(['ls','-l'], capture_output=True,text=True)print(result.stdout)
单元测试
import unittestdef add(a, b): return a + bclass TestMath(unittest.TestCase): def test add(self): self.assertEqual(add(1,2)3) self.assertEqual(add(-1,1),0) def test add fail(self): self.assertNotEqual(add(1,1),3)
性能测量
import time, timeitdef measure(): start = time.time() result = sum(range(1000000)) print(f"耗时:{time.time()- start}秒") return result
函数缓存提高性能
from functools import lru_cache@lru_cache(maxsize=128)def fibonacci(n): if n <= 1: return n return fibonacci(n-1)+ fibonacci(n-2)
命名元组
from collections import namedtuplePoint = namedtuple('Point',['x','y'])p= Point(3,4)print(p.x,p.y) # 通过名称访问元素
枚举类型
from enum import Enum,autoclass Color(Enum): RED = 1 GREEN = 2 BLUE = auto() # 自动赋值
数据类
from dataclasses import dataclass@dataclass class Product: name: str price: float quantity:int= 0 def total_cost(self)-> float: return self.price * self.quantity
安全哈希
import hashlibmd5 = hashlib.md5("password".encode()).hexdigest()sha256 = hashlib.sha256("password".encode()).hexdigest()
密码安全哈希
import hashlib, ossalt = os.urandom(16)hash = hashlib.pbkdf2_hmac( 'sha256', b'password',salt, 100000).hex()
安全随机数与UUID
import secretsimport uuidtoken=secrets.token_hex(16) # 32字符的安全随机令牌secure_num=secrets.randbelow(100) # 0-99的安全随机数user_id =uuid.uuid4() #随机UUID