Python是一種高級編程語言,它廣泛應用於各種領域,包括Web開發、數據分析和人工智慧等。一個強大的編程語言除了語法規則和基本數據類型外,還需要擁有豐富的模塊庫來支持各種功能的實現。Python標準庫中內置了很多常用的模塊,本文將介紹一些Python模塊的常用名稱及其功能。
一、os模塊
os模塊提供了與操作系統交互的功能,包括文件和目錄操作、與進程交互等功能。其常用功能如下:
1、創建和刪除目錄:os.mkdir(『dirname』); os.rmdir(『dirname』);
import os if not os.path.exists('testdir'): os.mkdir('testdir') else: os.rmdir('testdir')
2、獲取當前工作目錄:os.getcwd()
import os print(os.getcwd())
3、獲取文件路徑和文件名:os.path.split(『path/filename』);
import os path, filename = os.path.split('/etc/passwd') print(path) print(filename)
4、運行shell命令:os.system(『shell command』);
import os os.system('ls -l')
二、datetime模塊
datetime模塊提供了日期和時間的處理功能。其常用功能如下:
1、獲取當前日期和時間:datetime.datetime.now();
import datetime now = datetime.datetime.now() print(now)
2、格式化輸出日期和時間:strftime()方法。
import datetime now = datetime.datetime.now() print(now.strftime('%Y-%m-%d %H:%M:%S'))
3、計算日期:timedelta()方法。
import datetime today = datetime.date.today() oneday = datetime.timedelta(days=1) yesterday = today - oneday print(yesterday)
三、re模塊
re模塊提供了正則表達式處理功能,可用於匹配和替換字元串等。其常用功能如下:
1、匹配字元串:re.match(pattern, string);
import re s = 'hello world' match = re.match(r'(\w+)\s+(\w+)', s) print(match.group(1)) print(match.group(2))
2、查找字元串:re.search(pattern, string);
import re s = 'hello world' match = re.search(r'(\w+)\s+(\w+)', s) print(match.group(1)) print(match.group(2))
3、替換字元串:re.sub(pattern, repl, string);
import re s = 'hello world' new_s = re.sub(r'(\w+)\s+(\w+)', r'\2 \1', s) print(new_s)
四、sqlite3模塊
sqlite3是Python內置的輕型關係型資料庫,其常用功能如下:
1、創建資料庫連接並創建表:sqlite3.connect(database);
import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''') conn.commit() conn.close()
2、插入和查詢數據:c.execute(sql);c.fetchone();c.fetchall()。
import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") c.execute("SELECT * FROM stocks") print(c.fetchone()) print(c.fetchall()) conn.commit() conn.close()
以上就是一些Python模塊的常用名稱及其功能的介紹,通過使用這些模塊,可以更加方便地進行Python編程。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/271585.html