1.2.7. Standard Library¶
Note
Reference document for this section:
The Python Standard Library documentation: https://docs.python.org/3/library/index.html
Python Essential Reference, David Beazley, Addison-Wesley Professional
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_m90drc5z',
'profile_fry76cgz',
'profile_2yrlvikf',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-polkit.service-eBcLpU',
'clr-debug-pipe-1743-15174-out',
'profile_d_zz5eee',
'profile_7c4018q_',
'profile_3c5u7kk2',
'profile_d676drbd',
'profile_0z25ncw4',
'profile_ff9buazg',
'profile_sevem09z',
'profile_f1ebph6j',
'profile_r5gfx41o',
'profile_d6rjf37m',
'hsperfdata_root',
'profile_uo2pq7zu',
'profile_q5o1h5cg',
'profile_xd_i647j',
'clr-debug-pipe-834-1065-out',
'profile_8kue9me2',
'profile_cnxt1zu0',
'profile_dtuby8fu',
'profile_y8bpa_a6',
'profile_v9vbzu1y',
'clr-debug-pipe-1725-14915-out',
'profile_r9s319j3',
'profile_8bg844x8',
'clr-debug-pipe-834-1065-in',
'.X11-unix',
'.XIM-unix',
'profile_xnk70f1y',
'profile_hdbr2fsb',
'profile_wq660aav',
'.ICE-unix',
'profile_flc_3g1d',
'profile_yr6ka_d_',
'profile_szgpdyu6',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-systemd-logind.service-zt4ugW',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-chrony.service-Xqw0B4',
'profile_j8b0bwxg',
'profile_zq2u2npv',
'profile_ha6tylv2',
'profile_r30v5whe',
'dotnet-diagnostic-1743-15174-socket',
'profile_ekg3k9ib',
'profile_v39_xyr2',
'profile_rdzgkw6t',
'profile_zpaihoo5',
'profile_bpbgqd_2',
'profile_7aif4a7p',
'profile_0bwm4mmf',
'profile_du94w6ch',
'profile_qnnxmvgx',
'profile_ksyc6g6b',
'profile_5fdhkx0m',
'profile_9hkw0ydi',
'profile_gflxgl5u',
'profile_29hsshhv',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-ModemManager.service-TGvHjg',
'profile_t4fwjpl3',
'profile_5jvi1meb',
'profile_4mbjq44a',
'profile_8c8mogbh',
'.font-unix',
'snap-private-tmp',
'profile_ej23lcu_',
'profile_0axja7u4',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-haveged.service-sjEoj5',
'dotnet-diagnostic-1725-14915-socket',
'profile_oy_7fah2',
'profile_fs97slle',
'systemd-private-c06ff0f5e11f4f589c2722ac1610a93a-systemd-resolved.service-mHxQje',
'profile_ou9_knf2',
'profile_zefdd86m',
'profile_4p4m1nd8',
'profile_f2u7d4bu',
'profile_uh3ifl2q',
'profile_6uwtsy4f',
'profile__mj8bgjp',
'profile_wp4hb9ln',
'dotnet-diagnostic-834-1065-socket',
'profile_yx3if7co',
'profile_ylakqaxv',
'profile_b03ptn3h',
'profile_jc0p_wx5',
'profile_nws0hfe6',
'profile_2gq92qnj',
'profile_xu9zuern',
'clr-debug-pipe-1725-14915-in',
'clr-debug-pipe-1743-15174-in']
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-1743-15174-out
/tmp/clr-debug-pipe-834-1065-out
/tmp/clr-debug-pipe-1725-14915-out
/tmp/clr-debug-pipe-834-1065-in
/tmp/dotnet-diagnostic-1743-15174-socket
/tmp/dotnet-diagnostic-1725-14915-socket
/tmp/dotnet-diagnostic-834-1065-socket
/tmp/junk.txt
/tmp/clr-debug-pipe-1725-14915-in
/tmp/clr-debug-pipe-1743-15174-in
/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
/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
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.9 (main, Feb 5 2025, 03:22:31) [GCC 13.3.0]'
In [41]: sys.prefix
Out[41]: '/opt/hostedtoolcache/Python/3.12.9/x64'
List of command line arguments passed to a Python script:
In [42]: sys.argv
Out[42]:
['/opt/hostedtoolcache/Python/3.12.9/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.9/x64/lib/python312.zip',
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12',
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/lib-dynload',
'/opt/hostedtoolcache/Python/3.12.9/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']