1.2.7. 標準ライブラリ

注釈

このセクションの参考文献:

1.2.7.1. os モジュール: オペレーティングシステム機能

"オペレーティングシステムに依存する機能を使用するポータブルな方法。"

ディレクトリとファイルの操作

現在のディレクトリ:

In [1]: import os
In [2]: os.getcwd()
Out[2]: '/tmp'

ディレクトリのリスト:

In [3]: os.listdir(os.curdir)
Out[3]:
['profile_2bmdv5lg',
'profile_3eix4am_',
'profile_dlgqxrox',
'profile__is2zfz7',
'profile_nvfflga5',
'profile_j05ykn_j',
'profile_6kff6qy9',
'profile_bxqtntj0',
'profile_bef5vdkk',
'profile_5og5mczk',
'profile_8vnfy56q',
'profile_j52z8wnk',
'profile_6xmqvhhw',
'profile_kfpjm2cg',
'profile_xyrg6axm',
'profile_4qj0fbau',
'profile_li3h8wno',
'profile_p8ak0qiw',
'profile_th7sa_fo',
'profile_vvd68q2e',
'profile_4bcwoofj',
'profile_frm3wc0p',
'profile_uipja4ut',
'profile_itpg36_z',
'profile_vvoyfkub',
'profile_d1qgyk2b',
'profile_e9q90157',
'profile_nu7h6t1w',
'profile_jofvv0ob',
'profile_a_ezdmi_',
'profile_7xfswvrx',
'profile_70uvao82',
'profile_lfa4qg2b',
'profile_incstec6',
'profile_tqdhi0ii',
'profile_voxn8ldh',
'profile_mbr3y9ce',
'profile_4ehxl2ye',
'profile_4zesovdc',
'profile_o2grs5kb',
'profile_95oq9z1c',
'profile_djy5alfd',
'profile__b66ulcf',
'profile_8ikot2t1',
'profile_pgqty8rv',
'profile_oqhlt9k_',
'profile_eep7eln3',
'profile_nwkg3k0s',
'profile_2bvuwzwn',
'profile_51oxbi8z',
'profile_uglhmg2g',
'profile_fcsuerb6',
'profile_9320h1vq',
'profile_l3wflaui',
'profile_n55ltocj',
'profile_5w2hie36',
'profile_49_4hb_l',
'profile_hbx0cfuy',
'profile_7ymwk9l4',
'profile_vb8spukd',
'profile_rwih0t6i',
'profile_wmeob7g8',
'profile_fsa1y_qv',
'profile_yly67gk0',
'profile_s09rd_lc',
'profile_epdocwum',
'profile_l01hhbf8',
'profile__r5jh1r9',
'profile_pdij3m32',
'profile_zumy0pif']

ディレクトリを作ります:

In [4]: os.mkdir('junkdir')
In [5]: 'junkdir' in os.listdir(os.curdir)
Out[5]: True

ディレクトリ名を変更します:

In [6]: os.rename('junkdir', 'foodir')
In [7]: 'junkdir' in os.listdir(os.curdir)
Out[7]: False
In [8]: 'foodir' in os.listdir(os.curdir)
Out[8]: True
In [9]: os.rmdir('foodir')
In [10]: 'foodir' in os.listdir(os.curdir)
Out[10]: False

ファイルを削除します:

In [11]: fp = open('junk.txt', 'w')
In [12]: fp.close()
In [13]: 'junk.txt' in os.listdir(os.curdir)
Out[13]: True
In [14]: os.remove('junk.txt')
In [15]: 'junk.txt' in os.listdir(os.curdir)
Out[15]: False

os.path: path manipulations

os.path provides common operations on pathnames.

In [16]: fp = open('junk.txt', 'w')
In [17]: fp.close()
In [18]: a = os.path.abspath('junk.txt')
In [19]: a
Out[19]: '/tmp/junk.txt'
In [20]: os.path.split(a)
Out[20]: ('/tmp', 'junk.txt')
In [21]: os.path.dirname(a)
Out[21]: '/tmp'
In [22]: os.path.basename(a)
Out[22]: 'junk.txt'
In [23]: os.path.splitext(os.path.basename(a))
Out[23]: ('junk', '.txt')
In [24]: os.path.exists('junk.txt')
Out[24]: True
In [25]: os.path.isfile('junk.txt')
Out[25]: True
In [26]: os.path.isdir('junk.txt')
Out[26]: False
In [27]: os.path.expanduser('~/local')
Out[27]: '/home/docs/local'
In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin')
Out[28]: '/home/docs/local/bin'

Running an external command

In [29]: os.system('ls')
Out[29]: 0

注釈

Alternative to os.system

A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways to obtain the output, error stream and exit code of the external command.

In [30]: import sh
In [31]: com = sh.ls()
In [31]: print(com)
basic_types.rst exceptions.rst oop.rst standard_library.rst
control_flow.rst first_steps.rst python_language.rst
demo2.py functions.rst python-logo.png
demo.py io.rst reusing_code.rst
In [32]: type(com)
Out[32]: str

Walking a directory

os.path.walk generates a list of filenames in a directory tree.

In [33]: for dirpath, dirnames, filenames in os.walk(os.curdir):
....: for fp in filenames:
....: print(os.path.abspath(fp))
....:
....:
/tmp/junk.txt
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/bookmarks
/tmp/dhist
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README

Environment variables:

In [34]: os.environ.keys()
Out[34]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...}))
In [35]: os.environ['SHELL']
Out[35]: '/bin/bash'

1.2.7.2. shutil: high-level file operations

The shutil provides useful file operations:

  • shutil.rmtree: Recursively delete a directory tree.

  • shutil.move: Recursively move a file or directory to another location.

  • shutil.copy: Copy files or directories.

1.2.7.3. glob: Pattern matching on files

The glob module provides convenient file pattern matching.

Find all files ending in .txt:

In [36]: import glob
In [37]: glob.glob('*.txt')
Out[37]: ['junk.txt']

1.2.7.4. sys module: system-specific information

System-specific information related to the Python interpreter.

  • Which version of python are you running and where is it installed:

In [38]: import sys
In [39]: sys.platform
Out[39]: 'linux'
In [40]: sys.version
Out[40]: '3.12.10 (main, May 6 2025, 10:49:23) [GCC 11.4.0]'
In [41]: sys.prefix
Out[41]: '/home/docs/checkouts/readthedocs.org/user_builds/scientific-python-lectures-ja/envs/latest'
  • List of command line arguments passed to a Python script:

In [42]: sys.argv
Out[42]:
['/home/docs/checkouts/readthedocs.org/user_builds/scientific-python-lectures-ja/envs/latest/lib/python3.12/site-packages/sphinx/__main__.py',
'-T',
'-b',
'html',
'-d',
'_build/doctrees',
'-D',
'language=ja',
'.',
'/home/docs/checkouts/readthedocs.org/user_builds/scientific-python-lectures-ja/checkouts/latest/_readthedocs//html']

sys.path is a list of strings that specifies the search path for modules. Initialized from PYTHONPATH:

In [43]: sys.path
Out[43]:
['/home/docs/checkouts/readthedocs.org/user_builds/scientific-python-lectures-ja/checkouts/latest/scientific-python-lectures',
'/home/docs/.asdf/installs/python/3.12.10/lib/python312.zip',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/lib-dynload',
'/home/docs/checkouts/readthedocs.org/user_builds/scientific-python-lectures-ja/envs/latest/lib/python3.12/site-packages']

1.2.7.5. pickle: easy persistence

Useful to store arbitrary objects to a file. Not safe or fast!

In [44]: import pickle
In [45]: l = [1, None, 'Stan']
In [46]: with open('test.pkl', 'wb') as file:
....: pickle.dump(l, file)
....:
In [47]: with open('test.pkl', 'rb') as file:
....: out = pickle.load(file)
....:
In [48]: out
Out[48]: [1, None, 'Stan']

The PYTHONPATH Search Solution