0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】よく使う標準モジュールと関数まとめ(Python3エンジニア認定基礎試験対策)

Posted at

Pythonには便利な標準ライブラリが多数用意されています。
本記事では、Python3エンジニア認定基礎試験にも登場する主要モジュールとその関数を、ジャンルごと・使用頻度順に簡単な説明と例とともにまとめました。


📚 掲載モジュール一覧(ジャンル別)

  • 📁 ファイル・ディレクトリ操作系:os, shutil, glob
  • 💻 システム操作:sys
  • 🔍 テキスト処理:re
  • 🧮 計算・統計・乱数:math, random, statistics
  • 🌐 Webアクセス:urllib.request
  • 🗓️ 日付・時間:datetime
  • 🧩 ツール系:zlib, timeit, doctest, unittest
  • 🧼 表示整形・文字列操作:reprlib, pprint, textwrap, locale, string
  • 🧱 データ構造・バイナリ操作:struct, logging, threading, weakref, gc, array, collections, heapq, bisect

📁 ファイル・ディレクトリ操作系

osモジュール

OS(Operating System)とのやり取りを行うためのモジュールです。

os.getcwd()

現在の作業ディレクトリを取得します。

import os
print(os.getcwd())

os.chdir(path)

作業ディレクトリを変更します。

os.chdir("..")

os.listdir(path)

指定したディレクトリ内のファイル・フォルダ一覧を取得します。

print(os.listdir("."))

os.system(command)

シェルコマンドをPythonから実行します。

os.system("echo Hello")

shutilモジュール

ファイルやディレクトリのコピー・移動などを簡単に行うことができるモジュールです。

shutil.copyfile(src, dst)

ファイルをコピーします。

import shutil
shutil.copyfile("a.txt", "b.txt")

shutil.move(src, dst)

ファイルを移動します。

shutil.move("b.txt", "dir/b.txt")

globモジュール

ワイルドカードを使ってファイル名を検索できるモジュールです。

glob.glob(pattern)

パターンに一致するファイルをリストで返します。

import glob
print(glob.glob("*.txt"))

💻 システム操作・引数・標準入出力

sysモジュール

Pythonインタプリタとのやりとりに使われます。

sys.argv

コマンドライン引数をリストで取得します。

import sys
print(sys.argv)

sys.stdin / sys.stdout / sys.stderr

標準入力・出力・エラー出力を扱います。

for line in sys.stdin:
    sys.stdout.write(line)

🔍 テキスト処理・正規表現

reモジュール

正規表現を使って文字列の検索や置換を行うモジュールです。

re.findall(pattern, string)

マッチした文字列をリストで取得します。

import re
print(re.findall(r"\d+", "123abc456"))

re.sub(pattern, repl, string)

マッチ部分を別の文字列に置き換えます。

print(re.sub(r"\d+", "#", "abc123def456"))

🧮 計算・統計・乱数

mathモジュール

数学関数を提供するモジュールです。

math.sqrt(x)

平方根を返します。

import math
print(math.sqrt(16))

math.log(x)

自然対数を返します。

print(math.log(10))

math.sin(x)

ラジアンの正弦を返します。

print(math.sin(math.pi / 2))

math.pi

円周率πの定数です。

print(math.pi)

randomモジュール

ランダムな値を生成するモジュールです。

random.choice(seq)

シーケンスからランダムに1つ選択します。

import random
print(random.choice(["晴れ", "雨", "曇り"]))

random.sample(population, k)

ランダムにk個抽出します。

print(random.sample(range(10), 3))

statisticsモジュール

統計量を計算するモジュールです。

statistics.mean(data)

平均を返します。

import statistics
print(statistics.mean([1, 2, 3]))

statistics.median(data)

中央値を返します。

print(statistics.median([1, 3, 2]))

statistics.variance(data)

分散を返します。

print(statistics.variance([1, 2, 3]))

statistics.stdev(data)

標準偏差を返します。

print(statistics.stdev([1, 2, 3]))

🌐 Webアクセス

urllib.requestモジュール

WebページやAPIからデータを取得するモジュールです。

urllib.request.urlopen(url)

URLにアクセスしてデータを取得します。

import urllib.request
response = urllib.request.urlopen("https://example.com")
print(response.read())

🗓️ 日付・時間

datetimeモジュール

日時の取得や整形を行うモジュールです。

datetime.now()

現在日時を取得します。

from datetime import datetime
print(datetime.now())

datetime.utcnow()

UTC現在時刻を取得します。

print(datetime.utcnow())

datetime.strftime(format)

日時を指定フォーマットで文字列に変換します。

now = datetime.now()
print(now.strftime("%Y-%m-%d %A"))

🧩 ツール・ユーティリティ系

zlibモジュール

データを圧縮・展開します。

zlib.compress(data)

バイト列を圧縮します。

import zlib
compressed = zlib.compress(b"hello")
print(compressed)

zlib.decompress(data)

圧縮データを展開します。

print(zlib.decompress(compressed))

timeitモジュール

コードの実行時間を測定します。

timeit.timeit(stmt, number)

処理時間を返します。

import timeit
print(timeit.timeit("sum(range(100))", number=1000))

doctestモジュール

ドキュメントに書かれた例をテストとして実行できます。

doctest.testmod()

doctestを実行します。

def add(a, b):
    """
    >>> add(1, 2)
    3
    """
    return a + b

import doctest
doctest.testmod()

unittestモジュール

ユニットテスト用の標準モジュールです。

unittest.TestCase

テストクラスを作成します。

import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 2, 3)

if __name__ == "__main__":
    unittest.main()

🧼 表示整形・文字列操作

reprlibモジュール

出力を省略付きで整形するモジュールです。

reprlib.repr(obj)

長いリストや文字列を省略して表示します。

import reprlib
print(reprlib.repr(list(range(100))))

pprintモジュール

整形出力を行うモジュールです。

pprint.pprint(obj)

ネストされたデータ構造を見やすく表示します。

import pprint
data = {"fruits": ["apple", "banana"], "prices": {"apple": 100}}
pprint.pprint(data)

textwrapモジュール

文字列の整形・折り返しを行うモジュールです。

textwrap.fill(text, width)

指定幅で改行付き文字列を生成します。

import textwrap
print(textwrap.fill("Pythonが楽しい。" * 5, width=20))

textwrap.wrap(text, width)

リスト形式で文字列を折り返します。

print(textwrap.wrap("Pythonが楽しい。" * 5, width=20))

localeモジュール

ロケール(言語・地域)情報を扱います。

locale.getlocale()

現在のロケールを取得します。

import locale
print(locale.getlocale())

locale.setlocale(category, locale)

ロケールを変更します。

locale.setlocale(locale.LC_ALL, "ja_JP.UTF-8")

stringモジュール

テンプレート文字列などの機能を提供します。

string.Template

変数を埋め込んだテンプレート文字列を作成します。

from string import Template
t = Template("こんにちは、$nameさん!")
print(t.substitute(name="Python"))

🧱 データ構造・バイナリ操作

structモジュール

バイナリとPythonのデータ型を相互変換します。

struct.pack(format, value)

数値をバイト列に変換します。

import struct
print(struct.pack("i", 123))

loggingモジュール

ログ出力を管理するモジュールです。

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("debugログ")
logging.error("errorログ")

threadingモジュール

マルチスレッド処理を行うモジュールです。

import threading

def task():
    print("処理中...")

t = threading.Thread(target=task)
t.start()

weakrefモジュール

オブジェクトの弱参照を作成します。

import weakref

class MyClass:
    pass

obj = MyClass()
d = weakref.WeakValueDictionary()
d["key"] = obj
print(d["key"])

gcモジュール

ガベージコレクション(メモリ解放)を操作します。

import gc
gc.collect()

arrayモジュール

型付きの軽量な配列を作成できます。

import array
a = array.array("i", [1, 2, 3])
print(a)

collectionsモジュール

便利なデータ構造(例:deque)を提供します。

from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
print(d)

heapqモジュール

ヒープ(優先度付きキュー)操作を行います。

import heapq
h = [5, 1, 3]
heapq.heapify(h)
heapq.heappush(h, 2)
print(heapq.heappop(h))

bisectモジュール

ソート済みリストへの高速な挿入ができます。

import bisect
a = [1, 3, 5]
bisect.insort(a, 4)
print(a)

🔗 参考リンク

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?