📜  Python数据访问教程(1)

📅  最后修改于: 2023-12-03 15:04:39.657000             🧑  作者: Mango

Python数据访问教程

Python 是一种功能强大的编程语言,特别擅长数据处理和访问。这个教程介绍了如何使用 Python 访问各种数据存储,如文件系统、数据库、web服务等等。

文件系统

Python 提供了丰富的文件处理函数和库,使用 Python 可以轻松访问文件系统。以下是 Python 文件处理的两个例子:

# 读取文件内容
with open('sample.txt', 'r') as f:
    content = f.read()
    print(content)

# 写入文件内容
with open('sample.txt', 'w') as f:
    f.write('Hello, World!')
数据库

Python 支持连接多种类型的数据库,如 MySQL、PostgreSQL、SQLite 等等。以下是 Python 连接 MySQL 数据库的示例:

import mysql.connector

cnx = mysql.connector.connect(user='username', password='password',
                              host='127.0.0.1', database='mydatabase')
cursor = cnx.cursor()

query = ("SELECT id, name, age FROM mytable WHERE age = %s")

cursor.execute(query, (18,))

for (id, name, age) in cursor:
    print("{}, {}, {}".format(id, name, age))

cursor.close()
cnx.close()
Web服务

Python 通过 HTTP 库支持与web服务器的通信。下面是一个简单的使用 Python 与 Web 服务器进行交互的示例:

import requests

response = requests.get("https://api.github.com/users/username/repos")
data = response.json()

for repo in data:
    print(repo['name'])

以上仅仅是 Python 数据访问的一小部分,Python 还具有丰富的第三方库和框架,通过它们很容易地实现数据操作任务。希望这个教程有助于你理解 Python 的数据访问能力。