思不磕网-你身边的文案专家

思不磕网-你身边的文案专家

python软件如何读取数据

59

Python 提供了丰富的文件操作和数据读取功能,涵盖文本文件、数据库、网络数据源等多种类型。以下是主要方法及示例:

一、基础文件读取方法

使用 `open()` 函数

- 支持多种模式:`'r'`(只读)、`'w'`(写入)、`'a'`(追加)、`'x'`(独占创建)、`'b'`(二进制)、`'t'`(文本)、`'+'`(读写)

- 示例:

```python

读取文件内容

with open('example.txt', 'r', encoding='utf-8') as f:

content = f.read()

print(content)

```

```python

逐行读取

with open('large_file.txt', 'r') as f:

for line in f:

print(line.strip())

```

使用内置模块

- `csv` 模块:

读写 CSV 文件

```python

import csv

with open('test.csv', 'r', encoding='utf-8') as f:

reader = csv.reader(f)

for row in reader:

print(row)

```

- `pathlib` 模块:面向对象的文件操作

```python

from pathlib import Path

content = Path('example.txt').read_text(encoding='utf-8')

print(content)

```

二、进阶数据读取技巧

分块读取大文件

- 使用 `read()` 方法时指定 `chunksize` 参数,避免一次性加载整个文件

```python

with open('large_file.txt', 'r', encoding='utf-8') as f:

for chunk in iter(lambda: f.read(1024), b''):

process(chunk)

```

- 使用 Pandas 的 `read_csv()` 配置 `chunksize`

```python

import pandas as pd

for chunk in pd.read_csv('large_dataset.csv', chunksize=10000):

process(chunk)

```

数据库读取

- 使用 `sqlite3` 模块连接 SQLite 数据库

```python

import sqlite3

conn = sqlite3.connect('example.db')

cursor = conn.cursor()

cursor.execute("SELECT * FROM table_name")

data = cursor.fetchall()

conn.close()

```

- 使用 `SQLAlchemy` 连接其他数据库(如 MySQL、PostgreSQL)

```python

from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://user:password@localhost/database')

data = pd.read_sql("SELECT * FROM table_name", engine)

```

网络数据获取

- 使用 `requests` 库获取 JSON 数据

```python

import requests

response = requests.get('https://api.example.com/data')

data = response.json()

print(data)

```

- 使用 `BeautifulSoup` 爬取网页数据

```python

from bs4 import BeautifulSoup

response = requests.get('https://example.com')

soup = BeautifulSoup(response.text, 'html.parser')

data = soup.find_all('div', class_='target-class')

```

三、注意事项

文件路径:

使用相对路径或绝对路径,确保文件存在且权限正确

编码问题:读取文本文件时指定 `encoding`(如 `utf-8`),避免乱码

资源管理:使用 `with` 语句自动关闭文件,避免资源泄漏

通过以上方法,可以灵活应对不同数据源的读取需求。