# 读取文件
with open('file.txt', 'r') as file:
content = file.read()
# 写入文件
with open('file.txt', 'w') as file:
file.write('Hello, World!')
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
import json
# JSON字符串转字典
data = json.loads('{"name": "John", "age": 30}')
# 字典转JSON字符串
json_string = json.dumps(data)
import re
text = "Find all matches in this text"
matches = re.findall(r'\bma\w+', text)
from datetime import datetime
# 当前时间
now = datetime.now()
# 格式化日期时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
import random
# 随机整数
rand_num = random.randint(1, 100)
# 从另一个列表创建新列表
squares = [x * x for x in range(10)]
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
try:
result = 10 / 0
except ZeroDivisionError:
print("Divided by zero!")
```
10. 文件和目录操作
```python
import os
# 获取当前工作目录
cwd = os.getcwd()
# 列出目录内容
entries = os.listdir(cwd)
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())
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("example.com", 80))
from threading import Thread
def print_numbers():
for i in range(1, 6):
print(i)
thread = Thread(target=print_numbers)
thread.start()
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
from bs4 import BeautifulSoup
import requests
response = requests.get('http://example.com')
soup = BeautifulSoup(response.content, 'html.parser')
titles = soup.find_all('h1')
# 获取列表中的偶数
even_numbers = [x for x in range(10) if x % 2 == 0]
import os
for root, dirs, files in os.walk('/path/to/folder'):
for file in files:
print(os.path.join(root, file))
# 创建和使用字典
capitals = {'USA': 'Washington D.C.', 'France': 'Paris', 'Italy': 'Rome'}
print(capitals['France'])
# 使用lambda表达式进行排序
items = [{'name': 'John', 'age': 30}, {'name': 'Alice', 'age': 25}]
sorted_items = sorted(items, key=lambda x: x['age'])
# 读取每行内容
with open('file.txt', 'r') as file:
for line in file:
print(line.strip())
# 使用生成器产生斐波那契数列
def fib(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for num in fib(10):
print(num)
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()
# 集合的创建和操作
a_set = {1, 2, 3}
a_set.add(4)
a_set.remove(2)
# 枚举列表中的元素
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
import argparse
parser = argparse.ArgumentParser(description='Example script.')
parser.add_argument('name', help='Your name')
args = parser.parse_args()
print(f"Hello, {args.name}")
import os
# 读取环境变量
db_host = os.environ.get('DB_HOST', 'localhost')
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()
import pandas as pd
# 读取CSV文件
df = pd.read_csv('data.csv')
# 数据分析操作,例如计算平均值
print(df['column_name'].mean())
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 6]
plt.plot(x, y)
plt.show()
from PIL import Image
# 打开图像
image = Image.open('image.jpg')
# 应用图像处理,例如旋转
image = image.rotate(90)
# 保存图像
image.save('rotated_image.jpg')
这些代码片段覆盖了Python编程中的常见场景和操作。