python模块之OS、sys and JSON
模块是python中很重要的部分,其实一个.py文件就是一个模块。
模块有如下几种:
最重要的模块:os、sys、json、re(尤其是正则表达式)、logging、configparser、XML<我对这个学艺不精>
来吧,一个一个的过一下。
1、 os模块
--主要是与操作系统进行交互
def makedirs(name, mode=0o777, exist_ok=False):
"""makedirs(name [, mode=0o777][, exist_ok=False])
---可递归创建目录
Super-mkdir; create a leaf directory and all intermediate ones. Works like
mkdir, except that any intermediate path segment (not just the rightmost)
will be created if it does not exist. If the target directory already
exists, raise an OSError if exist_ok is False. Otherwise no exception is
raised. This is recursive.
"""
def removedirs(name):
"""removedirs(name)
---一删除空目录,,如果上一级目录也是空的,会一并删除。
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
"""
def renames(old, new):
"""renames(old, new)
---给文件或目录改名字
Super-rename; create directories as necessary and delete any left
empty. Works like rename, except creation of any intermediate
directories needed to make the new pathname good is attempted
first. After the rename, directories corresponding to rightmost
path segments of the old name will be pruned until either the
whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made
if you lack permissions needed to unlink the leaf directory or
file.
"""
def walk(top, topdown=True, onerror=None, followlinks=False):
"""Directory tree generator.
---找到目录结构,top代表的是要找到的目标目录,返回一个迭代器,可用next()方法,返回的是一个由三个元素
组成的元组。
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
举例:
import os
res = os.walk(r'D:\adef')
print(res)
print(next(res))
print(next(res))
print(next(res))
输出结果:
<generator object walk at 0x000002856881FE08>
('D:\\adef', ['def'], ['sc.log', '新建文本文档.txt'])
('D:\\adef\\def', ['test'], [])
('D:\\adef\\def\\test', [], ['hhh.txt'])
def execl(file, *args):
"""execl(file, *args)
替换现在运行的程序
Execute the executable file with argument list args, replacing the
current process. """
execv(file, args)
2、sys模块
(1)sys.path
---查找当前环境变量
(2)sys.exit()
---退出程序
3、json模块 ********非常重要
----用于跨平台进行数据交换,比如C语言中没有元组、列表的概念,只有数组的概念,怎么在C语言和python之间进行交互呢,就要有个中间人做衔接,json就起到了这个桥梁作用。先把数据转换成json模式,然后再解析为最初的格式。
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, sort_keys=False, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
----将python对象转换为JSON字符串,并将该字符串写入文件中。语法是接收两个参数,一个是python对象,一个是要写入的文件对象。
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, sort_keys=False, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
----将python对象转换为JSON字符串并返回该字符串,语法是接收一个python对象作为参数。
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
----读取文件,并转换为python对象。
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
----读取JSON字符串,并转换为python对象。
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).