Python 關鍵字



Python 的 with 關鍵字替換了 try-finally 塊。它是 區分大小寫的。它可以用於檔案處理和資料庫處理。支援 with 語句的函式或類被稱為 上下文管理器

上下文管理器允許您在需要時開啟和關閉資源。例如,open() 函式就是一個上下文管理器。當我們使用 with 語句呼叫 open() 函式時,檔案會在我們處理完檔案後自動關閉。

語法

以下是 Python with 關鍵字的語法:

with

在檔案中使用 'with' 關鍵字

with 關鍵字用於在檔案中 開啟特定檔案並執行各種操作。

示例

在這裡,我們使用 with 關鍵字以 讀取模式打開了 sample.txt 檔案:

def Tutorialspoint():
	with open('sample.txt') as Tp:
		data = Tp.read()
    # Printing our text
	print(data)
    
Tutorialspoint()

輸出

以下是上述程式碼的輸出:

Hello welcome to Tutorialspoint

在資料庫中使用 'with' 關鍵字

with 語句對於管理資料庫連線很有用,即使發生錯誤也能確保連線關閉。

示例

以下是 with 在資料庫中的用法示例:

import sqlite3

with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('Python',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('Java',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('C',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('C++',))
    conn.commit()

# Fetching data
with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users')
    print(cursor.fetchall())

輸出

以下是上述程式碼的輸出:

[(1, 'Python'), (2, 'Java'), (3, 'C'), (4, 'C++')]
python_keywords.htm
廣告

© . All rights reserved.