Python高级语法

Ptyhon高级语法

模块

  • 一个模块就是一个包含Python代码的文件
  • 后缀名就是.py
  • 用模块的好处
    • 程序太大,维护非常不方便,需要拆分
    • 模块化可以增加代码复用性
    • 当作命名空间使用,避免命名冲突
  • 模块定义方式
    • 模块就是一个Python文件,直接编写代码即可
    • 但是根据模块的规范,最好包括以下内容
      • 函数(单一功能)
      • 类(相似功能的组合,或者类似业务模块)
      • 测试代码(方便别人使用和扩展)

模块引用方式

  • 直接引用模块名(文件名)
import module_name
from module_name import *
module_name.function_name()
module_name.class_name()
  • 引用模块并起别名
import module_name as another_name
  • 引用模块中的特定内容
    • 推荐用这种方式,避免了代码的冗余
from module_name import function_name, class_name
function_name()
class_name()
  • 引用后,实际上等于把模块里面的代码粘贴进本文件并从头到尾执行一遍
  • 为了避免文件作为模块被引用时自动运行主函数,建议在程序入口前加入
if __name__ == '__main__':
  • 假如模块名称直接以数字开头,需要借助importlib模块帮助导入
import importlib
variable_name = importlib.import_module('file_name')

模块的搜索路径和存储

  • 搜索路径
    • 加载模块的时候,系统会自动通过搜索路径寻找到此模块
显示搜索路径
  • 使用sys模块
  • 使用sys.path属性获取路径列表
# 显示系统默认的模块搜索路径案例
import sys

print(type(sys.path))
for p in sys.path:
    print(p)
    
"""
运行结果:
<class 'list'>
D:\Study Codes\Python\AdvancedSyntax
D:\Study Codes\Python\AdvancedSyntax
C:\Users\Lyy\AppData\Local\JetBrains\PyCharm 2018.3.5\helpers\pycharm_display
D:\Study Codes\Python\AdvancedSyntax\venv\Scripts\python37.zip
C:\Users\Lyy\Anaconda3\DLLs
C:\Users\Lyy\Anaconda3\lib
C:\Users\Lyy\Anaconda3
D:\Study Codes\Python\AdvancedSyntax\venv
D:\Study Codes\Python\AdvancedSyntax\venv\lib\site-packages
D:\Study Codes\Python\AdvancedSyntax\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg
D:\Study Codes\Python\AdvancedSyntax\venv\lib\site-packages\pip-19.0.3-py3.7.egg
C:\Users\Lyy\AppData\Local\JetBrains\PyCharm 2018.3.5\helpers\pycharm_matplotlib_backend
"""
添加搜索路径
  • sys.path.append(dir)
模块的加载顺序
  1. 先搜索内存中已经加载好的模块
  2. 搜索Python的内置模块
  3. 搜索sys.path的路径

  • 包是一种组织管理代码的方式,包里面存放的是模块
  • 用于将模块包含在一起的文件夹就是包

包的结构

|--- 包
|---|--- __init__.py(包的标志文件)
|---|--- 模块1
|---|--- 模块2
|---|--- 子包(子文件夹)
|---|---|--- __init__.py(包的标志文件)
|---|---|--- 子包模块1
|---|---|--- 子包模块2

包的导入及操作

  • import package_name
    • 默认对__init__.py内容进行导入
    • __init__.py正常来说应该是空的
    • 使用方法
      • package_name.function_name()
      • package_name.class_name()
  • import package_name.module_name
    • 导入包中某一个具体的模块
    • 不会导入__init__.py的内容
    • 使用方法
      • package_name.module_name.function_name()
      • package_name.module_name
  • from package_name import module_name…
    • 不会导入__init__.py的内容
    • 使用方法
      • module_name.function_name()
      • module_name…class_name()
  • from package_name import *
    • 导入当前包中文件__init__.py的内容
    • 使用方法
      • function_name()
      • class_name()
  • from package_name.module_name import *
    • 导入包中指定模块的所有内容
    • 不会导入__init__.py的内容
    • 使用方法
      • function_name()
      • class_name()
  • __all__的用法
    • 在使用from package_name import *时,可以指定*可导入的内容
    • __init__.py中如果没有__all__,那么只可以把__init__中的内容导入
    • 如果__init__.py中设置了__all__的值,则按照__all__指定的子包或者模块进行导入,且不会导入__init__中的内容
    • 使用方法:__all__ = ['module1', 'module2', 'package1'...]

命名空间

  • 用于区分不同位置不同功能但相同名称的函数或者变量的一个特定前缀
  • 作用时防止命名冲突
  • 导入不同的包,实际上就导入了不同的命名空间
  • 不同的包里,可以有相同名字的函数、类和变量

异常

  • 广义上的错误分为错误和异常
  • 错误是人为可以避免的
  • 异常是指在语法逻辑正确的前提下出现的问题
  • 在Python中,异常是一个类,可以处理和使用

Python标准异常

  • BaseException:所有异常的基类
  • SystemExit:解释器请求退出
  • KeyboardInterrupt:用户中断执行(通常是输入^C)
  • Exception:常规错误的基类
  • StopIteration:迭代器没有更多的值
  • GeneratorExit:生成器(generator)发生异常来通知退出
  • StandardError:所有的内建标准异常的基类
  • ArithmeticError:所有数值计算错误的基类
  • FloatingPointError:浮点计算错误
  • OverflowError:数值运算超出最大限制
  • ZeroDivisionError:除(或取模)零 (所有数据类型)
  • AssertionError:断言语句失败
  • AttributeError:对象没有这个属性
  • EOFError:没有内建输入,到达EOF标记
  • EnvironmentError:操作系统错误的基类
  • IOError:输入/输出操作失败
  • OSError:操作系统错误
  • WindowsError:系统调用失败
  • ImportError:导入模块/对象失败
  • LookupError:无效数据查询的基类
  • IndexError:序列中没有此索引(index)
  • KeyError:映射中没有这个键
  • MemoryError:内存溢出错误(对于Python解释器不是致命的)
  • NameError:未声明/初始化对象(没有属性)
  • UnboundLocalError:访问未初始化的本地变量
  • ReferenceError:弱引用(Weak reference)试图访问已经垃圾回收了的对象
  • RuntimeError:一般的运行时错误
  • NotImplementedError:尚未实现的方法
  • SyntaxError:Python语法错误
  • IndentationError:缩进错误
  • TabError:Tab 和空格混用
  • SystemError:一般的解释器系统错误
  • TypeError:对类型无效的操作
  • ValueError:传入无效的参数
  • UnicodeError:Unicode相关的错误
  • UnicodeDecodeError:Unicode解码时的错误
  • UnicodeEncodeError:Unicode编码时错误
  • UnicodeTranslateError:Unicode转换时错误
  • Warning:警告的基类
  • DeprecationWarning:关于被弃用的特征的警告
  • FutureWarning:关于构造将来语义会有改变的警告
  • OverflowWarning:旧的关于自动提升为长整型(long)的警告
  • PendingDeprecationWarning:关于特性将会被废弃的警告
  • RuntimeWarning:可疑的运行时行为(runtime behavior)的警告
  • SyntaxWarning:可疑的语法的警告
  • UserWarning:用户代码生成的警告

异常类的继承关系

  • 在Python中,各种异常错误都是类,所有的错误类型都继承于BaseException
  • 在用try…except…finally…机制处理异常的时候,一定要注意异常的继承关系
    • 应该把越具体(子类)的异常放在越前面
    • 例如在except中如果有StandardError,那么永远也捕获不到ValueError,因为ValueError是StandardError的子类,如果有,也被StandardError的except给捕获了
  • 常见异常类型的继承关系
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
    +-- StopIteration
    +-- StandardError
    |    +-- BufferError
    |    +-- ArithmeticError
    |    |    +-- FloatingPointError
    |    |    +-- OverflowError
    |    |    +-- ZeroDivisionError
    |    +-- AssertionError
    |    +-- AttributeError
    |    +-- EnvironmentError
    |    |    +-- IOError
    |    |    +-- OSError
    |    |        +-- WindowsError (Windows)
    |    |        +-- VMSError (VMS)
    |    +-- EOFError
    |    +-- ImportError
    |    +-- LookupError
    |    |    +-- IndexError
    |    |    +-- KeyError
    |    +-- MemoryError
    |    +-- NameError
    |    |    +-- UnboundLocalError
    |    +-- ReferenceError
    |    +-- RuntimeError
    |    |    +-- NotImplementedError
    |    +-- SyntaxError
    |    |    +-- IndentationError
    |    |         +-- TabError
    |    +-- SystemError
    |    +-- TypeError
    |    +-- ValueError
    |        +-- UnicodeError
    |            +-- UnicodeDecodeError
    |            +-- UnicodeEncodeError
    |            +-- UnicodeTranslateError
    +-- Warning
        +-- DeprecationWarning
        +-- PendingDeprecationWarning
        +-- RuntimeWarning
        +-- SyntaxWarning
        +-- UserWarning
        +-- FutureWarning
	    +-- ImportWarning
	    +-- UnicodeWarning
	    +-- BytesWarning

异常处理

  • 不能保证程序永远正确执行
  • 但是,能保证程序在最出现问题的情况下得到妥善的处理
  • Python异常处理语法
try:
    # 尝试实现某个操作
    # 如果没出现异常,任务顺利完成
    # 如果出现异常,将异常从当前代码块扔出去尝试解决异常
except error1:
    # 解决方案1:用于尝试在此处处理异常解决问题
except error2:
    # 解决方案2:用于尝试在此处处理异常解决问题
except (error1,error2):
    # 解决方案:尝试解决多个异常使用相同的处理方式
except:
    # 解决方案:所有异常的解决方案
else:
    # 如果没有出现异常,将会执行此处代码
finally:
    # 不管有没有异常都要执行的代码
  • 流程
    1. 执行try中的语句
    2. 如果出现异常,则在except语句中查找对应异常并进行处理
    3. 如果没有异常,则执行else语句内容
    4. 最后,执行finally语句
  • 除except(最少一个)以外,else和finally可选
  • 在处理异常的时候,一旦拦截到某一个异常,则不再继续往下查看
  • 最好在最后一个except写上except Exception as e:
# 异常案例1
try:
    num = int(input('请输入一个数字:'))
    rst = 100 / num
    print('计算结果是:{0}'.format(rst))
except:
    print('你特么的输入些啥玩意儿')
    # 退出程序
    exit()
    
"""
运行结果:
请输入一个数字:6six
你特么的输入些啥玩意儿
"""
# 异常案例2
try:
    num = int(input('请输入一个数字:'))
    rst = 100 / num
    print('计算结果是:{0}'.format(rst))
# 捕获异常后,把异常实例化,出错信息会在实例化中
# 如果时多个error的情况,需要把更具体的错误往前放
except ZeroDivisionError as e:
    print('你特么的输入些啥玩意儿!')
    print(e)
    # 退出程序
    exit()
except NameError as e:
    print('名字起错了')
    print(e)
    exit()
except AttributeError as e:
    print('属性有问题')
    print(e)
    exit()
except Exception as e:
    print('我也不知道什么错误')
    print(e)
    exit()
    
"""
运行结果:
请输入一个数字:madman
我也不知道什么错误
invalid literal for int() with base 10: 'madman'
"""

手动引发异常

  • 当用户希望自己引发一个异常的时候使用
  • 自定义异常必须时系统异常的字类
  • 引发异常关键字:raise
  • 语法:raise ErrorClassName
# raise异常案例
try:
    print('I love Python')
    print(3.1415926)
    # 手动引发一个异常
    raise ValueError
except NameError as e:
    print('NameError')
except ValueError as e:
    print('ValueError')
except Exception as e:
    print('Exception')
finally:
    print('finally')
    
"""
运行结果:
I love Python
3.1415926
ValueError
finally
"""
# raise自定义异常案例
# 自己定义异常
# 自定义异常必须是系统异常的子类
class MadmanValueError(ValueError):
    pass
try:
    print('I love Python')
    print(3.1415926)
    # 手动引发一个异常
    raise MadmanValueError
except NameError as e:
    print('NameError')
except MadmanValueError as e:
    print('MadmanValueError')
except ValueError as e:
    print('ValueError')
except Exception as e:
    print('Exception')
finally:
    print('finally')
    
"""
运行结果:
I love Python
3.1415926
MadmanValueError
finally
"""
# else语句案例
try:
    num = int(input('请输入一个数字:'))
    rst = 100 / num
    print('计算结果是:{0}'.format(rst))
except Exception as e:
    print('Exception')
else:
    print('No Exception')
finally:
    print('Finally')
    
"""
运行结果:
请输入一个数字:6
计算结果是:16.666666666666668
No Exception
Finally
"""

自定义异常

  • 只要是raise的异常,则推荐使用自定义异常
  • 在自定义异常的时候,一般包含以下内容
    • 自定义发生异常的异常代码
    • 自定义发生医生后的问题提示
    • 自定义发生异常的行数
  • 最终的目的是让程序员能够快速定位错误内容

常用模块

calendar模块

  • 跟日历相关的模块
calendar()
  • 获取某一年的日历
  • 参数
    • theyear:指定年份
    • w:每个日期之间的间隔字符数(默认w=2)
    • l:每周所占用的行数(默认l=1)
    • c:每个月之间的间隔字符数(默认c=6)
    • m:一行显示多少个月份(默认m=3)
  • 返回值为字符串类型
# calendar案例1
import calendar

cal = calendar.calendar(theyear=2019)
print(type(cal))
print(cal)

"""
运行结果:
<class 'str'>
                                  2019

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                   1  2  3
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       4  5  6  7  8  9 10
14 15 16 17 18 19 20      11 12 13 14 15 16 17      11 12 13 14 15 16 17
21 22 23 24 25 26 27      18 19 20 21 22 23 24      18 19 20 21 22 23 24
28 29 30 31               25 26 27 28               25 26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7             1  2  3  4  5                      1  2
 8  9 10 11 12 13 14       6  7  8  9 10 11 12       3  4  5  6  7  8  9
15 16 17 18 19 20 21      13 14 15 16 17 18 19      10 11 12 13 14 15 16
22 23 24 25 26 27 28      20 21 22 23 24 25 26      17 18 19 20 21 22 23
29 30                     27 28 29 30 31            24 25 26 27 28 29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                         1
 8  9 10 11 12 13 14       5  6  7  8  9 10 11       2  3  4  5  6  7  8
15 16 17 18 19 20 21      12 13 14 15 16 17 18       9 10 11 12 13 14 15
22 23 24 25 26 27 28      19 20 21 22 23 24 25      16 17 18 19 20 21 22
29 30 31                  26 27 28 29 30 31         23 24 25 26 27 28 29
                                                    30

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                         1
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8
14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15
21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22
28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29
                                                    30 31
"""
# calendar案例2
import calendar

cal = calendar.calendar(theyear=2019, l=0, c=5, m=2)
print(cal)

"""
运行结果:
                     2019

      January                  February
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                  1  2  3
 7  8  9 10 11 12 13      4  5  6  7  8  9 10
14 15 16 17 18 19 20     11 12 13 14 15 16 17
21 22 23 24 25 26 27     18 19 20 21 22 23 24
28 29 30 31              25 26 27 28

       March                    April
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
             1  2  3      1  2  3  4  5  6  7
 4  5  6  7  8  9 10      8  9 10 11 12 13 14
11 12 13 14 15 16 17     15 16 17 18 19 20 21
18 19 20 21 22 23 24     22 23 24 25 26 27 28
25 26 27 28 29 30 31     29 30

        May                      June
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
       1  2  3  4  5                     1  2
 6  7  8  9 10 11 12      3  4  5  6  7  8  9
13 14 15 16 17 18 19     10 11 12 13 14 15 16
20 21 22 23 24 25 26     17 18 19 20 21 22 23
27 28 29 30 31           24 25 26 27 28 29 30

        July                    August
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7               1  2  3  4
 8  9 10 11 12 13 14      5  6  7  8  9 10 11
15 16 17 18 19 20 21     12 13 14 15 16 17 18
22 23 24 25 26 27 28     19 20 21 22 23 24 25
29 30 31                 26 27 28 29 30 31

     September                 October
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
                   1         1  2  3  4  5  6
 2  3  4  5  6  7  8      7  8  9 10 11 12 13
 9 10 11 12 13 14 15     14 15 16 17 18 19 20
16 17 18 19 20 21 22     21 22 23 24 25 26 27
23 24 25 26 27 28 29     28 29 30 31
30

      November                 December
Mo Tu We Th Fr Sa Su     Mo Tu We Th Fr Sa Su
             1  2  3                        1
 4  5  6  7  8  9 10      2  3  4  5  6  7  8
11 12 13 14 15 16 17      9 10 11 12 13 14 15
18 19 20 21 22 23 24     16 17 18 19 20 21 22
25 26 27 28 29 30        23 24 25 26 27 28 29
                         30 31
"""
isleap()
  • 判断某一年是否闰年
  • 参数
    • year:年份
  • 返回值为布尔类型
# isleap案例
import calendar

isl = calendar.isleap(year=2000)
print(type(isl))
print(isl)

"""
运行结果:
<class 'bool'>
True
"""
leapdays()
  • 获取指定年份之间的闰年的个数
  • 参数
    • y1:y1 <= y2,y1包含
    • y2:y1 <= y2,y2不包含
  • 返回值为整型
# leapdays()案例
import calendar

lea = calendar.leapdays(y1=1996, y2=2019)
print(type(lea))
print(lea)

"""
运行结果:
<class 'int'>
6
"""
month()
  • 获取某个月的日历
  • 参数
    • theyear:指定年份
    • themonth:指定月份
    • w:每个日期之间的间隔字符数(默认w=0)
    • l:每周所占用的行数(默认l=0)
  • 返回值为字符串类型
# month()案例
import calendar

mon = calendar.month(theyear=2019, themonth=7)
print(type(mon))
print(mon)

"""
运行结果:
<class 'str'>
     July 2019
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
"""
monthrange()
  • 获取一个月是星期几开始和天数
  • 参数
    • year:年份
    • month:月份
  • 返回值是显示星期几和天数的元组
  • 注意:0-6表示周一到周日
# monthrange()案例
import calendar

mon = calendar.monthrange(year=2019, month=7)
print(type(mon))
print(mon)

"""
运行结果:
<class 'tuple'>
(0, 31)
"""
monthcalendar()
  • 返回一个月每天的矩阵列表
  • 参数
    • year:年份
    • month:月份
  • 返回值是一个二级列表
  • 注意:矩阵中没有天数用0表示
# monthcalendar()案例
import calendar

mon = calendar.monthcalendar(year=2019, month=8)
print(type(mon))
print(mon)

"""
运行结果:
<class 'list'>
[[0, 0, 0, 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, 0]]
"""
prcal()
  • 直接打印某年的日历
  • 是print和calendar的缩写
  • 参数
    • theyear:指定年份
    • w:每个日期之间的间隔字符数(默认w=0)
    • l:每周所占用的行数(默认l=0)
    • c:每个月之间的间隔字符数(默认c=6)
    • m:一行显示多少个月份(默认m=3)
  • 无返回值
# prcal()案例
import calendar

prc = calendar.prcal(theyear=2019)
print(type(prc))

"""
运行结果:
                                  2019

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                   1  2  3
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       4  5  6  7  8  9 10
14 15 16 17 18 19 20      11 12 13 14 15 16 17      11 12 13 14 15 16 17
21 22 23 24 25 26 27      18 19 20 21 22 23 24      18 19 20 21 22 23 24
28 29 30 31               25 26 27 28               25 26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7             1  2  3  4  5                      1  2
 8  9 10 11 12 13 14       6  7  8  9 10 11 12       3  4  5  6  7  8  9
15 16 17 18 19 20 21      13 14 15 16 17 18 19      10 11 12 13 14 15 16
22 23 24 25 26 27 28      20 21 22 23 24 25 26      17 18 19 20 21 22 23
29 30                     27 28 29 30 31            24 25 26 27 28 29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                         1
 8  9 10 11 12 13 14       5  6  7  8  9 10 11       2  3  4  5  6  7  8
15 16 17 18 19 20 21      12 13 14 15 16 17 18       9 10 11 12 13 14 15
22 23 24 25 26 27 28      19 20 21 22 23 24 25      16 17 18 19 20 21 22
29 30 31                  26 27 28 29 30 31         23 24 25 26 27 28 29
                                                    30

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                         1
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8
14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15
21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22
28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29
                                                    30 31
<class 'NoneType'>
"""
prmonth()
  • 直接打印某月的日历
  • 是print和month的缩写
  • 参数
    • theyear:指定年份
    • themonth:指定月份
    • w:每个日期之间的间隔字符数(默认w=0)
    • l:每周所占用的行数(默认l=0)
  • 无返回值
# prmonth()案例
import calendar

prm = calendar.prmonth(theyear=2019, themonth=8)
print(type(prm))

"""
运行结果:
    August 2019
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
<class 'NoneType'>
"""
weekday()
  • 获取某日是星期几
  • 参数
    • year:年份
    • month:月份
    • day:天数
  • 返回值是整型
  • 注意:0-6表示周一到周日
# weekday()案例
import calendar

wee = calendar.weekday(year=2019, month=7, day=30)
print(type(wee))
print(wee)

"""
运行结果:
<class 'int'>
1
"""

time模块

关于时间的知识
  • 时间戳
    • 一个时间的表示方法,根据不同的语言,可以是整数也可以是浮点数
    • 是从1970年1月1日0时0分0秒到现在所经历的秒数
    • 如果表示的时间时1970年以前或者太遥远的未来,可能出现异常
    • 32位操作系统能够支持到2038年
  • UTC时间
    • UTC又称为世界协调时间,以英国的格林尼治天文所在地区的时间作为参考时间,也叫世界标准时间
    • 中国时间是UTC+8(东八区)
  • 时间结构
    • 一个包含时间内容的时间元组结构
索引内容属性
0tm_year2019
1tm_mon1-12
2tm_mday1-31
3tm_hour0-23
4tm_min0-59
5tm_sec0-61(60表示闰秒,61保留值)
6星期几tm_wday0-6
7第几天tm_yday1-366
8夏令时m_isdst0, 1, -1
模块属性
timezone
  • 当前时区和UTC时间相差的秒数(在没有夏令时的情况下的间隔,东八区是-28800)
# timezone案例
import time

time = time.timezone
print(time)

"""
运行结果:
-28800
"""
altzone
  • 获取当前时区和UTC时间相差的秒数(在有夏令时的情况下的间隔,东八区是-32400)
# altzone案例
import time

alt = time.altzone
print(alt)

"""
运行结果:
-32400
"""
模块方法
time()
  • 得到时间戳
  • 返回值是一个浮点数
# time()案例
import time

time = time.time()
print(type(time))
print(time)

"""
运行结果:
<class 'float'>
1570519050.6453655
"""
localtime()
  • 得到当前时间的时间元组
  • 返回值是一个时间元组
# localtime()案例
import time

local = time.localtime()
print(type(local))
print(local)
# 可以通过点号操作符得到相应属性的内容
print(local.tm_year, local.tm_mon, local.tm_mday)

"""
运行结果:
<class 'time.struct_time'>
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=16, tm_sec=46, tm_wday=1, tm_yday=281, tm_isdst=0)
2019 10 8
"""
asctime()
  • 对时间元组进行字符串化
  • 参数
    • t:时间元组
  • 返回值是一个字符串
# asctime()案例
import time

local = time.localtime()
asc = time.asctime(local)
print(type(local))
print(local)
print(type(asc))
print(asc)

"""
运行结果:
<class 'time.struct_time'>
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=16, tm_sec=7, tm_wday=1, tm_yday=281, tm_isdst=0)
<class 'str'>
Tue Oct  8 15:16:07 2019
"""
ctime()
  • 获取字符串化后的当前时间
  • 返回值是一个字符串
# ctime()案例
import time

ctime = time.ctime()
print(type(ctime))
print(ctime)

"""
运行结果:
<class 'str'>
Tue Oct  8 15:15:27 2019
"""
mktime()
  • 使用时间元组获取对应的时间戳
  • 参数
    • t:时间元组
  • 返回值是一个浮点数时间戳,但是小数点后面为0且保留一位小数
# mktime()案例
import time

local = time.localtime()
mktime = time.mktime(local)
print(type(local))
print(local)
print(type(mktime))
print(mktime)

"""
运行结果:
<class 'time.struct_time'>
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=14, tm_sec=43, tm_wday=1, tm_yday=281, tm_isdst=0)
<class 'float'>
1570518883.0
"""
sleep()
  • 使程序进入睡眠状态,n秒后继续
  • 参数
    • seconds:秒数(整型浮点数都行)
  • 无返回值
# sleep()案例
import time

for i in range(0, 10):
    print(i)
    time.sleep(1.11)
strftime()
  • 将时间元组转化为自定义的字符串格式
  • 参数
    • format:自定义的格式
    • p_tuple:时间元组
  • 返回值是一个字符串
  • 时间日期格式化符号
    • %y:两位数的年份表示(00-99)
    • %Y:四位数的年份表示(000-9999)
    • %m:月份(01-12)
    • %d:月内中的一天(0-31)
    • %H:24小时制小时数(0-23)
    • %I:12小时制小时数(01-12)
    • %M:分钟数(00-59)
    • %S:秒(00-59)
    • %a:本地简化星期名称
    • %A:本地完整星期名称
    • %b:本地简化的月份名称
    • %B:本地完整的月份名称
    • %c:本地相应的日期表示和时间表示
    • %j:年内的一天(001-366)
    • %p:本地A.M.或P.M.的等价符
    • %U:一年中的星期数(00-53)星期天为星期的开始
    • %w:星期(0-6),星期天为星期的开始
    • %W:一年中的星期数(00-53)星期一为星期的开始
    • %x:本地相应的日期表示
    • %X:本地相应的时间表示
    • %Z:当前时区的名称
    • %%:%号本身
# strftime案例
# 将时间表示成:xxxx年xx月xx日 xx:xx
import time

local = time.localtime()
strf = time.strftime('%Y{y}%m{m}%d{d} %H{h}%M', local).format(y='年', m='月', d='日', h=':')
print(type(local))
print(local)
print(type(strf))
print(strf)

"""
运行结果:
<class 'time.struct_time'>
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=13, tm_sec=1, tm_wday=1, tm_yday=281, tm_isdst=0)
<class 'str'>
2019年10月08日 15:13
"""

datetime模块

  • datetime提供日期时间的运算和表示
模块属性
date
  • 一个日期类
  • 属性
    • year:年份,整型
    • month:月份,整型
    • day:日期,整型
# date案例
import datetime

date = datetime.date(2019, 7, 31)
print(type(date))
print(date)
print(type(date.year))
print(date.year)
print(type(date.month))
print(date.month)
print(type(date.day))
print(date.day)

"""
运行结果:
<class 'datetime.date'>
2019-07-31
<class 'int'>
2019
<class 'int'>
7
<class 'int'>
31
"""
time
  • 一个时间类,提供hour、minute、second、microsecond等属性
# time案例
import datetime

time = datetime.time(hour=12, minute=22, second=33, microsecond=44)

print(type(time.hour))
print(time.hour)
print(type(time.minute))
print(time.minute)
print(type(time.second))
print(time.second)
print(type(time.microsecond))
print(time.microsecond)

"""
运行结果:
<class 'int'>
12
<class 'int'>
22
<class 'int'>
33
<class 'int'>
44
"""
模块方法
today()、now()
  • 获得现在的时间,和初始化时输入的值无关,格式:yyyy-mm-dd hh:mm:ss.mmmmmm
  • 返回值是一个时间类型的时间
# today()、now()案例
import datetime

today = datetime.datetime(year=2019, month=8, day=5)
now = datetime.datetime(year=2019, month=8, day=5)
print(type(today.today()))
print(today.today())
print(type(now.now()))
print(now.now())

"""
运行结果:
<class 'datetime.datetime'>
2019-08-05 17:46:42.323248
<class 'datetime.datetime'>
2019-08-05 17:46:42.323248
"""
fromtimestamp()
  • 将时间戳格式转化为时间类型
  • 返回值是一个时间类型的时间
# fromtimestamp()案例
import datetime
import time

fts = datetime.datetime(year=2019, month=8, day=5)
time = time.time()
print(type(fts.fromtimestamp(time)))
print(fts.fromtimestamp(time))

"""
运行结果:
<class 'datetime.datetime'>
2019-08-05 17:50:56.760157
"""
timedelta()
  • 表示一个时间间隔
  • 参数
    • weeks:周数
    • days:天数
    • hours:小时数
    • minutes:分钟数
    • seconds:秒数
    • milliseconds:毫秒数
    • microseconds:微秒数
  • 返回值是一个时间类型的时间
# timedelta()案例
from datetime import datetime, timedelta

t1 = datetime.now()
print(type(t1))
print(t1)
print(type(t1.strftime('%Y-%m-%d %H:%M:%S')))
print(t1.strftime('%Y-%m-%d %H:%M:%S'))

# td表示以小时为单位的时间长度
td = timedelta(hours=1)

t2 = t1 + td
print(type(t2))
print(t2)
print(type(t2.strftime('%Y-%m-%d %H:%M:%S')))
print(t2.strftime('%Y-%m-%d %H:%M:%S'))

"""
运行结果:
<class 'datetime.datetime'>
2019-08-05 19:02:48.958506
<class 'str'>
2019-08-05 19:02:48
<class 'datetime.datetime'>
2019-08-05 20:02:48.958506
<class 'str'>
2019-08-05 20:02:48
"""
timeit模块
timeit()
  • 执行指定代码并返回执行时间
  • 参数:
    • stmt:要执行的字符串代码或者函数名
    • setup:执行代码的准备工作,不计入时间,一般是import
    • number:执行次数
  • 返回值是显示用时的浮点数
# timeit()案例1
import timeit
# 执行100000次,查看运行时间
t1 = timeit.timeit(stmt="[i for i in range(1000)]", number=100000)

c = '''
sum = []
for i in range(1000):
    sum.append(i)
'''
# 对c字符串执行100000次,查看运行时间
t2 = timeit.timeit(stmt=c, number=100000)
print(type(t1))
print(t1)
print(type(t2))
print(t2)

"""
运行结果:
<class 'float'>
3.2871785
<class 'float'>
6.679100900000001
"""
# timeit()案例2
import timeit

def do_it():
    num = 2
    for i in range(num):
        print('Repeat for {0}'.format(i))

# 执行函数,重复2次
t = timeit.timeit(stmt=do_it, number=2)
print(t)

"""
运行结果:
Repeat for 0
Repeat for 1
Repeat for 0
Repeat for 1
3.9600000000000746e-05
"""
# timeit()案例3
import timeit

s = """
def do_it(num):
    for i in range(num):
        print('Repeat for {0}'.format(i))
"""

# 执行函数,重复2次
t = timeit.timeit(stmt='do_it(num)', setup=s+'num=2', number=2)
print(type(t))
print(t)

"""
运行结果:
Repeat for 0
Repeat for 1
Repeat for 0
Repeat for 1
<class 'float'>
4.389999999998562e-05
"""

os模块

  • 和操作系统相关,主要是对文件进行操作
    • os:操作系统目录相关
    • os.path:系统路径相关操作
    • shutil:高级文件操作,目录树的操作、文件复制、操作、移动…
模块属性
curdir
  • 当前目录
  • 格式:os.curdir
# curdir案例
import os

print(type(os.curdir))
print(os.curdir)

"""
运行结果:
<class 'str'>
.
"""
pardir
  • 上一级目录
  • 格式:os.pardir
# pardir案例
import os

print(type(os.pardir))
print(os.pardir)

"""
运行结果:
<class 'str'>
..
"""
sep
  • 当前系统的路径分隔符
  • 格式:os.sep
# sep案例
import os

print(type(os.sep))
print(os.sep)

"""
运行结果:
<class 'str'>
\
"""
linesep
  • 当前系统的换行符
    • Windows:\r\n
    • Unix\Linux\MacOS:\n
  • 格式:os.linesep
# linesep案例
import os

print(type(os.linesep))
print(os.linesep)

"""
运行结果:
<class 'str'>

"""
name
  • 当前系统名称
  • 格式:os.name
# name
import os

print(type(os.name))
print(os.name)

"""
运行结果:
<class 'str'>
nt
"""
模块方法
getcwd()
  • 获取当前的工作目录
  • 格式:os.getcwd()
  • 返回值:当前工作目录的字符串
# getcwd()案例1
import os

mydir = os.getcwd()
print(type(mydir))
print(mydir)

"""
运行结果:
<class 'str'>
D:\Study Codes\Python\AdvancedSyntax
"""
chdir()
  • 改变当前的工作目录
  • 格式:os.chdir(dir)
  • 返回值:无
# chdir()案例
import os

chdir = os.chdir('D:\Study Codes\Python')
print(type(chdir))
print(chdir)
mydir = os.getcwd()
print(type(mydir))
print(mydir)

"""
运行结果:
<class 'NoneType'>
None
<class 'str'>
D:\Study Codes\Python
"""
listdir()
  • 获取一个目录中所有子目录和文件名
  • 格式:os.listdir(path)
  • 返回值:所有子目录和文件名的列表
  • 注意:如果没有指定路径时,默认是当前工作路径
# listdir()案例
import os

ld1 = os.listdir()
print(type(ld1))
print(ld1)

ld2 = os.listdir('D:\Study Codes\Python')
print(type(ld2))
print(ld2)

"""
运行结果:
<class 'list'>
['.idea', 'p01.py', 'p02.py', 'p03.py', 'p04.py', 'p05.py', 'p06.py', 'p07.py', 'pkg01', 'pkg02', 'test.py', 'venv', '__pycache__']
<class 'list'>
['AdvancedSyntax', 'OOP', 'Scrapy']
"""
makedirs()
  • 递归创建文件夹
  • 格式:os.makedirs(path)
  • 返回值:无
  • 注意:如果文件夹已存在,则执行会报错
# makedirs()案例
import os

try:
    mkdir = os.makedirs('Madman')
    print(type(mkdir))
    print(mkdir)
except FileExistsError as e:
    print(e)
finally:
    pass

"""
运行结果:
<class 'NoneType'>
None
"""
system()
  • 运行系统shell命令
  • 格式:os.system(command)
  • 返回值:0表示成功1表示失败,整型
# system()案例
import os

rst = os.system('exit()')
print(type(rst))
print(rst)

"""
运行结果:
<class 'int'>
0
"""
getenv()
  • 获取指定的系统环境变量值
  • 格式:os.getenv(env_name)
  • 返回值:指定环境变量名所对应的值,字符串格式
# getenv()案例
import os

rst = os.getenv('OS')
print(type(rst))
print(rst)

"""
运行结果:
<class 'str'>
Windows_NT
"""

os.path模块

  • 与路径相关的模块
模块方法
abspath()
  • 将路径转化为绝对路径
  • 格式:os.path.abspath(path)
  • 返回值:绝对路径字符串
# abspath()案例
import os.path

# "."号代表当前目录,".."代表上一级目录
absp = os.path.abspath('.')
print(type(absp))
print(absp)

"""
运行结果:
<class 'str'>
D:\Study Codes\Python\AdvancedSyntax
"""
basename()
  • 获取路径中的文件名部分
  • 格式:os.path.basename(path)
  • 返回值:文件名字符串
# abspath()案例
import os.path

bn = os.path.basename('haha/hehe/xixi')
print(type(bn))
print(bn)

"""
运行结果:
<class 'str'>
xixi
"""
join()
  • 将多个路径拼接成一个路径
  • 格式:os.path.join(path1, path2...)
  • 返回值:新路径字符串
# join()案例
import os.path

bd = 'one\\two'
fn = 'xixi.haha'

dir = os.path.join(bd, fn)
print(type(dir))
print(dir)

"""
运行结果:
<class 'str'>
one\two\xixi.haha
"""
split()
  • 将路径切割为文件夹部分和当前文件部分
  • 格式:os.path.split(path)
  • 返回值:路径和文件名组成的元组
# split()案例
import os.path

sp = os.path.split('one\\two\\xixi.haha')
print(type(sp))
print(sp)

bd, fn = os.path.split('one\\two\\xixi.haha')
print(type(bd), type(fn))
print(bd, fn)

"""
运行结果:
<class 'tuple'>
('one\\two', 'xixi.haha')
<class 'str'> <class 'str'>
one\two xixi.haha
"""
isdir()
  • 判断是否存在指定目录
  • 格式:os.path.isdir(path)
  • 返回值:True为是False为否,bool类型
# isdir()案例
import os.path as op

rst = op.isdir('D:\\Game')
print(type(rst))
print(rst)

"""
运行结果:
<class 'bool'>
True
"""
exists()
  • 判断文件或目录是否存在
  • 格式:os.path.exists(path)
  • 返回值:True为是False为否,bool类型
# exists()案例
import os.path as op

rst = op.exists('D:\\Game')
print(type(rst))
print(rst)

"""
运行结果:
<class 'bool'>
True
"""
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值