1.2.7. Standard Library

Note

Reference document for this section:

1.2.7.1. os module: operating system functionality

“A portable way of using operating system dependent functionality.”

Directory and file manipulation

Current directory:

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

List a directory:

In [3]: os.listdir(os.curdir)
Out[3]:
['profile_3rb29fpe',
'profile_oe30wxw_',
'profile_clk1t_rg',
'profile_29oi4jo5',
'profile_39pxye08',
'profile_p6v_v7sq',
'profile_ozjbnggz',
'profile_yj792c9i',
'profile_mljceg4r',
'profile_6e6zxeg8',
'clr-debug-pipe-603-920-in',
'systemd-private-ae700a37b6034453abbfa0848dcf3e27-chrony.service-jdA6z0',
'profile_3xpmtdd9',
'profile_rxlb82t1',
'clr-debug-pipe-1585-18465-out',
'profile_2bebomcz',
'profile_0v_u3utq',
'profile_gmn64ouf',
'profile_74ps3dvv',
'www-data-temp-aspnet-0',
'snap-private-tmp',
'systemd-private-ae700a37b6034453abbfa0848dcf3e27-systemd-resolved.service-WWrcN9',
'profile_ik0c5w1j',
'profile_cnw_7175',
'profile_mypj3gku',
'profile_fxix5sff',
'profile_akfaz8e1',
'.ICE-unix',
'profile_4hnmfvx_',
'clr-debug-pipe-1585-18465-in',
'profile_0o9ltv1j',
'.font-unix',
'profile_u_d66q2r',
'profile_nuilaxkx',
'.Test-unix',
'profile_mq7ar3z7',
'profile_ofb3ddh4',
'.XIM-unix',
'profile_iy1kos_8',
'profile_ygznuplk',
'profile_2k9_qbwx',
'systemd-private-ae700a37b6034453abbfa0848dcf3e27-haveged.service-nzu9dr',
'profile_mpnprwv6',
'profile_47isdgkb',
'profile_ax34id7n',
'profile_xypg_tw2',
'profile_f837wn58',
'profile_w349fmtc',
'profile_185surie',
'profile_e7ti0yxk',
'profile_fv77vr2c',
'profile_kftp_8ks',
'profile_rghjcsb1',
'profile_0ud4rep7',
'profile_63qgwkkr',
'profile_vpzedfrk',
'profile_z7eqla7s',
'profile_83mnqjge',
'profile_jrxywflo',
'profile_gr085ryv',
'profile_xn9r9dh_',
'profile_lh_9d491',
'dotnet-diagnostic-603-920-socket',
'systemd-private-ae700a37b6034453abbfa0848dcf3e27-systemd-logind.service-uT7rOR',
'profile_4bsp8k5h',
'clr-debug-pipe-603-920-out',
'profile_tsq7uqp3',
'profile_ehr748oc',
'profile_ewp3a_mm',
'clr-debug-pipe-1568-18286-out',
'profile_mu5lb7p_',
'dotnet-diagnostic-1585-18465-socket',
'profile_s9bk9imo',
'profile_03aoe_36',
'profile_kuvwr__7',
'profile_x5vqrl7y',
'profile_nija_y4w',
'profile_evtst6i0',
'dotnet-diagnostic-1568-18286-socket',
'profile_ik53wrdk',
'profile_ekuev8_w',
'.X11-unix',
'profile_4qld0cpn',
'clr-debug-pipe-1568-18286-in',
'profile_vf_2cx6d',
'profile_wfum51ib',
'profile_3am91xl3',
'profile_eygd6diu',
'profile_di1njky_',
'profile_2vex2ga3']

Make a directory:

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

Rename the directory:

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

Delete a file:

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/runner/local'
In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin')
Out[28]: '/home/runner/local/bin'

Running an external command

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

Note

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/clr-debug-pipe-603-920-in
/tmp/clr-debug-pipe-1585-18465-out
/tmp/clr-debug-pipe-1585-18465-in
/tmp/dotnet-diagnostic-603-920-socket
/tmp/clr-debug-pipe-603-920-out
/tmp/clr-debug-pipe-1568-18286-out
/tmp/dotnet-diagnostic-1585-18465-socket
/tmp/dotnet-diagnostic-1568-18286-socket
/tmp/clr-debug-pipe-1568-18286-in
/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/dhist
/tmp/bookmarks
/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/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.8 (main, Dec 4 2024, 06:19:59) [GCC 11.4.0]'
In [41]: sys.prefix
Out[41]: '/opt/hostedtoolcache/Python/3.12.8/x64'
  • List of command line arguments passed to a Python script:

In [42]: sys.argv
Out[42]:
['/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/sphinx/__main__.py',
'-b',
'latex',
'-d',
'build/doctrees',
'.',
'build/latex']

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

In [43]: sys.path
Out[43]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.12.8/x64/lib/python312.zip',
'/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12',
'/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/lib-dynload',
'/opt/hostedtoolcache/Python/3.12.8/x64/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