生活中实用的python代码
时间: 2024-11-05 19:11:44 浏览: 14
Python是一门功能强大的脚本语言,常用于数据处理、Web开发、科学计算等多个领域。下面是一些生活中实用的Python代码片段:
1. **文件操作**:例如读取文本文件内容:
```python
with open('file.txt', 'r') as file:
content = file.read()
print(content)
```
2. **日期时间处理**:
```python
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
```
3. **简单的数据分析** (使用pandas库):
```python
import pandas as pd
data = pd.read_csv('data.csv')
mean_value = data['column_name'].mean()
print(mean_value)
```
4. **网页抓取** (使用BeautifulSoup库):
```python
import requests
from bs4 import BeautifulSoup
response = requests.get('http://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string
print(title)
```
5. **发送邮件** (使用smtplib库):
```python
import smtplib
msg = "Subject: Test Email\n\nHello, this is a test email."
server = smtplib.SMTP('smtp.example.com')
server.sendmail("sender@example.com", "receiver@example.com", msg)
server.quit()
```
阅读全文