【代码片段】Python实用代码片段(一)

本文介绍了Python中关于文件操作(如读写、检查、流式传输)和基本HTTP请求(GET、POST、错误处理等)的实用代码片段,涵盖了文件I/O、网络通信的关键部分。
摘要由CSDN通过智能技术生成

咱们平时写程序代码一般都是按照程序功能点来设计和编写的,而代码片段正式这些小功能中最精华或者说核心的部分,因此这个系列咱们来看看Python中一些实用的代码片段。

我将内容分成了各个逻辑区域,这些区域通常是相互关联的,这样你就可以根据自己的兴趣,快速定位到与你目前任务或主题最相关的内容。这些内容包括文件操作、API 交互、电子表格处理、数学计算,以及处理列表和字典等数据结构。此外,我还会特别推荐一些有用的库,这些库在 Python 常见的应用领域中非常流行。

如果你觉得我漏掉了任何应该包含在速查表中的内容,请务必在评论中告诉我,我会及时更新列表!

文件操作技巧

1. 读取文件内容

要读取文件的全部内容:

with open('example.txt', 'r') as file:  
    content = file.read()  
    print(content)

2. 写入文件

要向文件写入文本,覆盖原有内容:

with open('example.txt', 'w') as file:  
    file.write('Hello, Python!')

3. 追加到文件末尾

要在现有文件末尾添加文本:

with open('example.txt', 'a') as file:  
    file.write('\n追加这一行。')

4. 读取行到列表中

要逐行读取文件内容并存入列表:

with open('example.txt', 'r') as file:  
    lines = file.readlines()  
    print(lines)

5. 逐行遍历文件内容

要逐行处理文件内容:

with open('example.txt', 'r') as file:  
    for line in file:  
        print(line.strip())

6. 检查文件是否存在

在进行文件操作之前,要检查文件是否存在:

import os  
if os.path.exists('example.txt'):  
    print('文件存在。')  
else:  
    print('文件不存在。')

7. 将列表写入文件

要将列表中的每个元素写入文件的新行:

lines = ['第一行', '第二行', '第三行']  
with open('example.txt', 'w') as file:  
    for line in lines:  
        file.write(f'{line}\n')

8. 使用 With 块处理多个文件

使用 with 块同时处理多个文件:

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:  
    content = source.read()  
    destination.write(content)

9. 删除文件

要安全地删除文件(如果存在):

import os  
if os.path.exists('example.txt'):  
    os.remove('example.txt')  
    print('文件已删除。')  
else:  
    print('文件不存在。')

10. 读写二进制文件

要以二进制模式读取和写入文件(对于图像、视频等很有用):

# 读取二进制文件  
with open('image.jpg', 'rb') as file:  
    content = file.read()  
# 写入二进制文件  
with open('copy.jpg', 'wb') as file:  
    file.write(content)

使用简单的 HTTP API

1. 基本的 GET 请求

使用 GET 请求从 API 端点获取数据:

import requests  
response = requests.get('https://api.example.com/data')  
data = response.json()  # 假设响应是 JSON 格式的  
print(data)

2. 带有查询参数的 GET 请求

发送带有查询参数的 GET 请求:

import requests  
params = {'key1': 'value1', 'key2': 'value2'}  
response = requests.get('https://api.example.com/search', params=params)  
data = response.json()  
print(data)

3. 处理 HTTP 错误

优雅地处理可能发生的 HTTP 错误:

import requests  
response = requests.get('https://api.example.com/data')  
try:  
    response.raise_for_status()  # 如果状态码是 4xx 或 5xx,则抛出 HTTPError  
    data = response.json()  
    print(data)  
except requests.exceptions.HTTPError as err:  
    print(f'HTTP 错误: {err}')

4. 为请求设置超时

设置请求的超时时间,以避免无限期挂起:

import requests  
try:  
    response = requests.get('https://api.example.com/data', timeout=5)  # 超时时间为 5 秒  
    data = response.json()  
    print(data)  
except requests.exceptions.Timeout:  
    print('请求超时')

5. 在请求中使用标头

在请求中包含标头(例如,用于授权):

import requests  
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}  
response = requests.get('https://api.example.com/protected', headers=headers)  
data = response.json()  
print(data)

6. 带有 JSON 负载的 POST 请求

使用带有 JSON 负载的 POST 请求向 API 端点发送数据:

import requests  
payload = {'key1': 'value1', 'key2': 'value2'}  
headers = {'Content-Type': 'application/json'}  
response = requests.post('https://api.example.com/submit', json=payload, headers=headers)  
print(response.json())

7. 处理响应编码

正确处理响应的编码:

import requests  
response = requests.get('https://api.example.com/data')  
response.encoding = 'utf-8'  # 设置编码以匹配预期的响应格式  
data = response.text  
print(data)

8. 使用会话对象处理请求

使用会话对象在同一主机上进行多个请求,可以提高性能:

import requests  
with requests.Session() as session:  
    session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})  
    response = session.get('https://api.example.com/data')  
    print(response.json())

9. 处理重定向

处理或禁用请求中的重定向:

import requests  
response = requests.get('https://api.example.com/data', allow_redirects=False)  
print(response.status_code)

10. 流式传输大型文件

流式传输大型响应以便逐块处理,而不是一次性加载到内存中:

import requests  
response = requests.get('https://api.example.com/large-data', stream=True)  
for chunk in response.iter_content(chunk_size=1024):  
    process(chunk)  # 用实际的处理函数替换 'process'

总结

本期主要讲了Python中如何进行文件操作及HTTP请求操作相关代码片段,关注我 下期更精彩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值