Python如何读取数据

Python作为一种广泛使用的编程语言,具有强大的数据处理能力,在数据处理过程中,读取数据是第一步,本文将详细介绍Python中读取数据的常用方法,包括从文件、数据库和网络等多种来源读取数据。
从文件读取数据
读取文本文件
在Python中,可以使用内置的open()函数和read()方法来读取文本文件,以下是一个简单的示例:
with open('example.txt', 'r') as file:
content = file.read()
print(content) 逐行读取文本文件
如果需要逐行读取文本文件,可以使用readlines()方法或者循环遍历文件对象,以下是一个使用循环遍历的示例:
with open('example.txt', 'r') as file:
for line in file:
print(line, end='') 读取二进制文件

对于二进制文件,可以使用open()函数的'rb'模式来读取,以下是一个示例:
with open('example.bin', 'rb') as file:
content = file.read()
print(content) 从数据库读取数据
使用SQLite数据库
Python内置了SQLite数据库的支持,可以使用sqlite3模块来读取数据,以下是一个示例:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close() 使用MySQL数据库
对于MySQL数据库,可以使用mysql-connector-python模块来读取数据,以下是一个示例:
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='user',
password='password',
database='database_name'
)
cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close() 从网络读取数据

- 使用
requests库读取网页内容
Python中可以使用requests库来发送HTTP请求,并获取网页内容,以下是一个示例:
import requests
response = requests.get('http://example.com')
print(response.text) - 使用
urllib库读取网页内容
Python内置的urllib库也可以用来读取网页内容,以下是一个示例:
import urllib.request
with urllib.request.urlopen('http://example.com') as response:
content = response.read()
print(content) FAQs
Q1:如何读取Excel文件中的数据? A1:可以使用openpyxl或pandas库来读取Excel文件中的数据,以下是一个使用pandas的示例:
import pandas as pd
df = pd.read_excel('example.xlsx')
print(df) Q2:如何读取JSON文件中的数据? A2:可以使用json模块来读取JSON文件中的数据,以下是一个示例:
import json
with open('example.json', 'r') as file:
data = json.load(file)
print(data) 
