1. 操作系统接口

os 模块提供了一些与操作系统相关联的函数。

>>> os.getcwd()             # 获取当前工作目录
'/home/senius'
>>> os.chdir('./Downloads') # 更改当前工作目录
>>> os.getcwd()
'/home/senius/Downloads'
>>> os.system('ls')         # 运行系统命令
4221d02a2e88e9053085920f13f9ce36.jpg
503c572dd0f9d734b55f1bd12765c4f8.jpg
c497770eca94fdf3baf4f813bafcb20a.jpg

>>> dir(os)                # 查看 os 模块所有的函数
>>> os.environ             # 获取系统的环境变量

2. 文件通配符

glob 模块提供了一个函数用于从目录通配符搜索中生成文件列表。

>>> import glob
>>> glob.glob('*.jpg')     # 返回当前目录下所有 JPG 图片的文件名
['c497770eca94fdf3baf4f813bafcb20a.jpg',
 '4221d02a2e88e9053085920f13f9ce36.jpg',
 '503c572dd0f9d734b55f1bd12765c4f8.jpg']
>>>

3. 命令行参数

在命令行中运行 python 命令时,这些参数会以列表形式保存在 sys 模块的 argv 变量中。

# test.py

import sys
print(sys.argv)

>>> python3 test.py 1 2 use_gpu=True
['test.py', '1', '2', 'use_gpu=True']

4. 日期和时间

datetime 模块为日期和时间处理同时提供了简单和复杂的方法。

>>> from datetime import date
>>> import datetime as dt
>>> now = date.today()
>>> now
datetime.date(2018, 10, 28)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'10-28-18. 28 Oct 2018 is a Sunday on the 28 day of October.'
>>>

>>> year = dt.timedelta(days=365) # 计算多少天之前的日期
>>> one_year_ago = now - year
>>> one_year_ago
datetime.date(2017, 10, 28)


>>> birthday = date(1997, 7, 1) # 日历运算
>>> age = now - birthday
>>> age.days
7789

>>> import calendar
>>> a = calendar.monthrange(2018, 10)
>>> a
(0, 31) # 10 月的第一天为周一,10 月总共有 31 天

# 生成日历
>>> print(calendar.month(2018, 10))
    October 2018
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31


参考资料 菜鸟教程

获取更多精彩,请关注「seniusen」!