1.2.7. 标准库¶
注意
本节参考文档
Python 标准库文档:https://docs.pythonlang.cn/3/library/index.html
Python Essential Reference, David Beazley, Addison-Wesley Professional
1.2.7.1. os
模块:操作系统功能¶
“一种使用操作系统相关功能的可移植方法。”
目录和文件操作¶
当前目录
In [1]: import os
In [2]: os.getcwd()
Out[2]: '/tmp'
列出目录
In [3]: os.listdir(os.curdir)
Out[3]:
['systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-systemd-logind.service-b9Rzjz',
'profile_aigtsgcb',
'profile_mmurb8al',
'profile_xvonz9yf',
'profile_4hs_w_mh',
'dotnet-diagnostic-1659-25920-socket',
'clr-debug-pipe-1659-25920-out',
'profile_lgnuvwyt',
'profile_8shzy308',
'profile_xcrx5vq8',
'profile_r8j35hgb',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-chrony.service-fI5AKM',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-haveged.service-mIZITo',
'snap-private-tmp',
'profile_4ikxwrj1',
'profile_t34k0xr8',
'profile_nl7kgt6g',
'profile_rts6jo7t',
'profile_sxoh34un',
'.Test-unix',
'profile_ho8psflt',
'profile_czgm0fx3',
'profile_9vkbhmz7',
'profile_fgaa3812',
'profile_31ggph82',
'profile_ecrzkms3',
'profile_4oyg93xr',
'dotnet-diagnostic-606-982-socket',
'profile_1_9wxfx4',
'profile_aq6t3dxq',
'profile_pulh7uyz',
'profile_5_tt0l9w',
'profile__ux3mc46',
'clr-debug-pipe-606-982-out',
'profile_vgmfv7ae',
'.X11-unix',
'.ICE-unix',
'.font-unix',
'profile_h7s5rvrk',
'profile_qsp3_q4p',
'profile_o23tpc6n',
'profile_wkzbriqc',
'clr-debug-pipe-606-982-in',
'profile_agvc7v4m',
'profile_j5riknag',
'systemd-private-adec3d1727fe4cd39ffbe00d42109bc0-systemd-resolved.service-LZYFSu',
'profile_kcc2n4g7',
'clr-debug-pipe-1641-25689-out',
'profile_9nz6obms',
'profile_z53xjajo',
'profile_ewil8srw',
'profile_bkzd2sj_',
'clr-debug-pipe-1641-25689-in',
'profile_zk2rhhsn',
'profile_aq3hxf0g',
'profile_ujt_dsv6',
'profile_pu0vk1xu',
'profile_dk_b2g1k',
'profile_9fsj2k75',
'profile_0m71mlo2',
'clr-debug-pipe-1659-25920-in',
'profile_q3_da92m',
'.XIM-unix',
'profile_o6gr3f53',
'profile_ud5som2r',
'www-data-temp-aspnet-0',
'profile_0h7ljo86',
'profile_9rpgis60',
'profile_4r0wr_uf',
'profile_evxijf16',
'profile_m23qdbuk',
'profile_xx29y4wl',
'profile_31xc2qwr',
'profile_kxp0ehvn',
'profile__2tb6hf4',
'profile_iatzm6x3',
'profile_r3xscs1p',
'profile_tk9omgbb',
'profile_37leef3_',
'profile_om7err07',
'profile_t7peg56y',
'profile_30z2ds56',
'profile_nnurehu6',
'profile__y38edp6',
'dotnet-diagnostic-1641-25689-socket',
'profile_4esqldpc',
'profile_az_xm5hv',
'profile_zzggzu6j',
'profile_j48t_pkc',
'profile_sjaajzbs']
创建目录
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
:路径操作¶
os.path
提供对路径名的常见操作。
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'
运行外部命令¶
In [29]: os.system('ls')
Out[29]: 0
注意
os.system
的替代方案
os.system
的一个值得注意的替代方案是 sh 模块。 它提供了更方便的方式来获取外部命令的输出、错误流和退出代码。
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
遍历目录¶
os.path.walk
生成目录树中的文件名列表。
In [33]: for dirpath, dirnames, filenames in os.walk(os.curdir):
....: for fp in filenames:
....: print(os.path.abspath(fp))
....:
....:
/tmp/dotnet-diagnostic-1659-25920-socket
/tmp/clr-debug-pipe-1659-25920-out
/tmp/dotnet-diagnostic-606-982-socket
/tmp/clr-debug-pipe-606-982-out
/tmp/clr-debug-pipe-606-982-in
/tmp/clr-debug-pipe-1641-25689-out
/tmp/clr-debug-pipe-1641-25689-in
/tmp/clr-debug-pipe-1659-25920-in
/tmp/junk.txt
/tmp/dotnet-diagnostic-1641-25689-socket
/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
/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
环境变量:¶
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
:高级文件操作¶
shutil
提供有用的文件操作
shutil.rmtree
:递归删除目录树。
shutil.move
:递归地将文件或目录移动到另一个位置。
shutil.copy
:复制文件或目录。
1.2.7.3. glob
:文件上的模式匹配¶
glob
模块提供了方便的文件模式匹配。
查找所有以 .txt
结尾的文件
In [36]: import glob
In [37]: glob.glob('*.txt')
Out[37]: ['junk.txt']
1.2.7.4. sys
模块:系统特定信息¶
与 Python 解释器相关的系统特定信息。
您正在运行哪个版本的 python 以及它安装在哪里
In [38]: import sys
In [39]: sys.platform
Out[39]: 'linux'
In [40]: sys.version
Out[40]: '3.12.6 (main, Sep 9 2024, 03:08:08) [GCC 11.4.0]'
In [41]: sys.prefix
Out[41]: '/opt/hostedtoolcache/Python/3.12.6/x64'
传递给 Python 脚本的命令行参数列表
In [42]: sys.argv
Out[42]:
['/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sphinx/__main__.py',
'-b',
'latex',
'-d',
'build/doctrees',
'.',
'build/latex']
sys.path
是一个字符串列表,指定模块的搜索路径。 从 PYTHONPATH 初始化
In [43]: sys.path
Out[43]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python312.zip',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/lib-dynload',
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages']
1.2.7.5. pickle
:简单的持久化¶
用于将任意对象存储到文件。 不安全或不快!
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']