Python是一門高級語言,常用於處理數據。在數據處理過程中,讀取數據是非常重要的一步,本篇文章將從多個方面來詳細闡述Python讀取數據。
一、文件讀取
Python可以打開、讀取、寫入文件。其中,文件讀取是其中的重要部分。
1、普通文本文件讀取:
# 讀取普通文本文件
with open('file_path/file_name.txt', 'r') as f:
# 每次讀取一行
line = f.readline()
while line:
print(line.strip())
line = f.readline()
其中file_path/file_name.txt
為文件的路徑和文件名。
2、CSV文件讀取:
# 讀取CSV文件
import csv
with open('file_path/file_name.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
其中file_path/file_name.csv
為文件的路徑和文件名。
3、Excel文件讀取:
# 讀取Excel文件
import xlrd
workbook = xlrd.open_workbook('file_path/file_name.xls')
sheet = workbook.sheet_by_index(0)
for row in range(1, sheet.nrows):
print(sheet.row_values(row))
其中file_path/file_name.xls
為文件的路徑和文件名。
二、網路數據讀取
Python能夠從網路中讀取數據,比如從API介面中得到數據。
1、讀取JSON格式數據:
# 讀取JSON格式數據
import json
import urllib.request
url = "http://example.com/api/data"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print(data)
其中http://example.com/api/data
為API介面地址。
2、讀取XML格式數據:
# 讀取XML格式數據
import xml.etree.ElementTree as ET
import urllib.request
url = "http://example.com/api/data"
response = urllib.request.urlopen(url)
data = response.read()
root = ET.fromstring(data)
for child in root:
print(child.tag, child.attrib)
其中http://example.com/api/data
為API介面地址。
三、資料庫讀取
Python能夠從資料庫中讀取數據,目前主要有MySQL和SQLite兩種。
1、讀取MySQL資料庫:
# 讀取MySQL資料庫
import pymysql
# 連接資料庫
conn = pymysql.connect(
host="localhost",
user="root",
password="password",
database="database_name"
)
# 獲取游標
cur = conn.cursor()
# 執行SQL語句
cur.execute("SELECT * FROM table_name")
# 獲取數據
data = cur.fetchall()
for row in data:
print(row)
# 關閉游標和連接
cur.close()
conn.close()
2、讀取SQLite資料庫:
# 讀取SQLite資料庫
import sqlite3
# 連接資料庫
conn = sqlite3.connect('database_name.db')
# 獲取游標
cur = conn.cursor()
# 執行SQL語句
cur.execute("SELECT * FROM table_name")
# 獲取數據
data = cur.fetchall()
for row in data:
print(row)
# 關閉游標和連接
cur.close()
conn.close()
以上為Python讀取數據的幾種常用方法。根據不同的數據類型和數據源,選擇不同的方法可以提高處理數據的效率。
原創文章,作者:ZYGIL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371042.html