Python实用模块推荐_click_pathlib

click是一个创建命令行接口的第三方python库,是Command Line Interface Creation Kit的缩写。click具有高度可配置、代码量更少、代码更加优雅等特点。是argparse的升级版。
安装click

pip install click
import click
@click.command()
@click.option(‘–count’, default=1, help=’Number of greetings.’)
@click.option(‘–name’, prompt=’Your name’,
help=’The person to greet.’)
def hello(count, name):
“””Simple program that greets NAME for a total of COUNT times.”””
for x in range(count):
click.echo(‘Hello %s!’ % name)
if __name__ == ‘__main__’:
hello()

@click.command()表示在某个方法上接收命令行参数,
@click.option表示跟的具体参数,一个参数接一个@click.option,
–count跟方法hello里的第一个参数名count保持一致。

pathlib模块

python本身是跨平台的编程语言,但是在处理文件路径时经常会碰到\(windows)和/(类unix)的问题,以前的做法可能是先判断下当前的系统平台,然后在做路径拼接(使用os.path对象)的时候选择适当的分隔符(\或者/)。pathlib这个模块就完美解决了这个问题,它是Python3.4之后的标准库,是比os.path更高抽象级别的对象。

from pathlib import Path

path = Path(__file__)
print(path.suffix)
print(path.stem)
print(path.name)
print(path.parent)
directory = Path(‘~’)
path2 = directory / ‘dj.jpeg’
print(path2)
Path的常用方法及属性
Path.is_dir() # 判断是否是目录
Path.resolve() # 返回绝对路径
Path.open() # 打开文件
Path.exists() # 是否存在
Path.iterdir() # 遍历目录的子目录或文件
Path.with_suffix() # 更改路径后缀
Path.joinpath() # 拼接路径
Path.stat() # 返回路径信息(同`os.stat()`)
Path.mkdir() # 创建目录
Path.rename() # 重命名路径
Path.root # 返回路径的根目录
Path.parents # 返回所有上级目录的列表
Path.drive # 返回驱动器名称

发表评论