iT邦幫忙

2024 iThome 鐵人賽

DAY 18
0
Python

Python探索之旅:從基礎到實踐系列 第 18

D18:數據大師之路 - 從 CSV 到 MySQL 與 Google 試算表的全面操作指南

  • 分享至 

  • xImage
  •  

1. 認識 CSV 檔案的儲存與讀取

CSV 是一種常用的純文本格式,儲存結構化數據簡單易懂,並且在數據交換中非常流行。利用 Python 的 csv 模組可以輕鬆操作這種檔案格式。

1.1 儲存數據到 CSV:

import csv

data = [
    ['Name', 'Age', 'City'],
    ['Alice', 23, 'New York'],
    ['Bob', 34, 'Los Angeles'],
    ['Charlie', 29, 'Chicago']
]

with open('people.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

1.2 讀取 CSV 文件:

import csv

with open('people.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

2. Excel 文件的儲存與讀取

Excel 檔案處理適合進行更高級的數據分析。透過 openpyxl 庫可以寫入和讀取 .xlsx 文件格式。

2.1 儲存數據到 Excel:

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

data = [
    ['Name', 'Age', 'City'],
    ['Alice', 23, 'New York'],
    ['Bob', 34, 'Los Angeles'],
    ['Charlie', 29, 'Chicago']
]

for row in data:
    ws.append(row)

wb.save('people.xlsx')

2.2 讀取 Excel 文件:

from openpyxl import load_workbook

wb = load_workbook('people.xlsx')
ws = wb.active

for row in ws.iter_rows(values_only=True):
    print(row)

3. MySQL 資料庫操作

MySQL 是一個流行的關聯型資料庫,適合儲存大規模結構化數據。透過 Python 的 mysql-connector 模組可以對 MySQL 資料庫進行操作。

3.1 建立資料庫和資料表:

import mysql.connector

# 連接 MySQL
conn = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="testdb"
)

cursor = conn.cursor()

# 創建資料表
cursor.execute("CREATE TABLE IF NOT EXISTS people (name VARCHAR(255), age INT, city VARCHAR(255))")

# 插入數據
sql = "INSERT INTO people (name, age, city) VALUES (%s, %s, %s)"
val = [("Alice", 23, "New York"), ("Bob", 34, "Los Angeles"), ("Charlie", 29, "Chicago")]
cursor.executemany(sql, val)

# 提交變更
conn.commit()

print(cursor.rowcount, "筆記錄已插入。")

# 查詢資料
cursor.execute("SELECT * FROM people")
result = cursor.fetchall()

for row in result:
    print(row)

# 關閉連接
conn.close()

3.2 查詢資料:

cursor.execute("SELECT * FROM people")
rows = cursor.fetchall()

for row in rows:
    print(row)

4. SQLite 資料庫操作

SQLite 是一個輕量級的嵌入式資料庫,適合小型應用程序。通過 sqlite3 模組,我們可以對 SQLite 資料庫進行操作。

4.1 建立資料庫和資料表:

import sqlite3

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

cursor.execute('''CREATE TABLE IF NOT EXISTS people
                  (name TEXT, age INTEGER, city TEXT)''')

cursor.execute("INSERT INTO people (name, age, city) VALUES ('Alice', 23, 'New York')")
cursor.execute("INSERT INTO people (name, age, city) VALUES ('Bob', 34, 'Los Angeles')")
cursor.execute("INSERT INTO people (name, age, city) VALUES ('Charlie', 29, 'Chicago')")

conn.commit()
conn.close()

5. Google 試算表操作

Google 試算表是一個雲端的數據處理工具,可以通過 API 操作試算表進行讀寫。我們使用 gspread 和 Google Sheets API 操作試算表。

5.1 連接 Google 試算表並寫入數據:

首先,你需要在 Google Cloud 註冊並啟用 Google Sheets API,並下載憑證 JSON 文件。

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 設定 API 範圍
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]

# 加載憑證
creds = ServiceAccountCredentials.from_json_keyfile_name('your_credentials.json', scope)
client = gspread.authorize(creds)

# 開啟 Google 試算表
sheet = client.open('Test Spreadsheet').sheet1

# 寫入數據到 Google 試算表
data = ["Alice", 23, "New York"]
sheet.append_row(data)

5.2 讀取 Google 試算表的數據:

# 讀取數據
records = sheet.get_all_records()
for record in records:
    print(record)

總結:

透過本次學習,我們探索了從簡單的 CSV 文件到 Google 試算表的數據操作過程,並熟悉了 MySQL 和 SQLite 這兩種流行的資料庫系統。無論是本地數據處理還是雲端資料管理,這些工具都能大大提高我們的工作效率。


上一篇
DAY 17: 網路數據獵人——用 BeautifulSoup 精準爬取大樂透開獎號碼
下一篇
D19:數據的藝術 - 透視台灣股市的視覺化魔法
系列文
Python探索之旅:從基礎到實踐27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言