Python basis (xv)

Today the main content

  • Module acquaintance
    • Import module
    • Module Path
    • Custom Modules
  • Built-in module (standard library)
    • time
    • datetime
    • random
    • sys
    • the
    • funtools

First, the module acquaintance

(A) What is a module

  • In fact, every py file we created is a module, the module is a function of the different functions are classified, divided, packaged collection
  • Module Category:
    • Built-in module (standard library)
    • Third-party modules (third-party libraries)
    • Custom Modules
  • Features module: ism
    • Development of high efficiency, there is no need to know which principles
    • Reduce duplication of code
    • Sub file management, help to modify and maintain

(B) introducing the module

  1. Import Module Keywords: Import

  2. Only in import module for the first time will be performed, in order to prevent duplication of import, python after the first imported in the name of the load module into memory, again just import the module is loaded into memory objects increases the time it is referenced, will not be repeated statements within the execution module

    # text.py文件
    print("这是text.py文件中的语句")
    def func():
     print("这是text.py文件中的函数")
    
    # target.py文件
    import text
    import text
    import text
    
    运行结果:
    这是text.py文件中的语句  # 只运行一次
  3. The first occurred when importing three things:

    • The source file (imported modules) to create a new namespace, function or method defined in the imported module is used to access the global namespace
    • Code contained in the module execute in the name of the newly created space in
    • Create a module name to refer to the name of the same name space
  4. Find the order import modules

    • Memory> Built-in> sys.path
    • Description: When running the interpreter, will be part of the common module is loaded into memory, when we import the module interpreter to find out if this module has been loaded into memory, if not go to find there is no such built-in library module If no final look sys.pathof the module contains the path, import, if not, the interpreter will be given
    • Path module may be added by manually added to sys.paththe, sys.pathreturns a list, can be used append()addition method, the interpreter for the search
    from sys import path
    path.append(r"C:\Users\11582\Desktop")
    
    from text import ceshi
    ceshi()
  5. Module method of introduction:

    • import XXX: All imported module
    • from XXX import XXX: Specifies import function module
    • In later use as, both of which are introduced to the module or function rename
    import time as a
    from time import sleep as s
    • Description:

      • Use importimport line can be introduced into a plurality of modules, but not recommended, to use a recommended every importimport only one module
      import time
      import random
      import sys
      • Use frommay be introduced into the line a plurality of functions, function introduced before the variable definition with the same name will be overwritten when using
      def time():
         print("123")
      
      from time import time
      time()
      
      运行结果:
      123
      • from XXX import *: Introducing all the functions within a module, by __all__limiting import function
      # 被导入文件:zxd.py
      def name():
         print("zxd")
      
      def age():
         print("age")
      
      __all__ = ["name"]
      
      # 运行文件:target.py
      from zxd import *
      
      age()
      
      运行结果:
      NameError: name 'age' is not defined
  6. Two uses modules

    • As a general module execution
    • As a script execution
  7. How to use the function module

    • powerful.
    • If using importimport an entire module, when used to take advantage of模块名.功能
    import time 
    
    t = time.time()
    • If you are using from, you can directly use this feature, so pay attention to the previously defined function overrides
    def time():
     print("123")
    
    from time import time
    time()
    
    运行结果:
    123
  8. Avoid circular import module

    • Three modules, an import module 2, module 3 import module 2, module 3 import module 1 ( avoid )

(Iii) a custom module

  • Note: Do not define the same built-in module module name custom module

  • py files you created is a custom module

    # zxd.py  # 自定义模块
    def name():
      print("zxd")
    
    def age():
      print("age")
    
    # target.py
    import zxd
    
    zxd.name()
    zxd.age()
    
    运行结果:
    zxd
    23
    
  • Private part definition module (not by the introduction of the use)

    if __name__ == "__main__":
      """私有部分"""
    
    • How it works: If you __name__run this document is returned __main__if the return is being imported imported file name.
    # zxd.py文件
    print(__name__)
    if __name__ == "__main__":
      """私有部分"""
    
    运行结果:
    __main__
    
    # zxd.py文件
    print(__name__)
    if __name__ == "__main__":
      """私有部分"""
    
    # target.py文件
    import zxd
    
    print(__name__)
    
    运行结果:
    zxd
    __main__
    

Second, the built-in module (standard library)

(A) time module

  1. and a time module is time dependent module in python, python time is divided into three forms:

    • Timestamp: 1970-01-01 00:00:00 From now experienced a total number of seconds, represented by float

    • Structured time: in the form of tuples to a fixed structure of the output time

      • Fixed structure: year, month, day, hour, minute, second, the first few weeks of the year, day of the year, whether it is summer time (daylight saving time is 1; 0 is non-daylight saving time, -1 for sure whether Daylight Saving time)
      time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
      
    • Formatting time: according to our need to format any time

      • Format standard:
      %Y Two-digit year representation (00-99)
      % Y (common) Four-digit year representation (000-9999)
      % M (common) Month (01-12)
      % D (common) Within a month of the day (0-31)
      % H (common) 24-hour number (0-23) hours
      %I 12-hour number (01-12) h
      % M (common) The number of minutes (00 = 59)
      % S (common) Sec (00-59)
      %a Local simplify week name
      %A Local full weekday name
      %b Local simplify month name
      %B Local full month name
      %c Local representation appropriate date and time representation
      %j Day (001-366) during the year
      %p Local AM or PM equivalent character
      % U Weeks of the year (00-53) for the week beginning Sunday
      %w Week (0-6), Sunday is the start of week
      %W Weeks of the year (00-53) for the week beginning Monday
      %x Corresponding date local representation
      %X Represents the corresponding local time
      %WITH Name of the current time zone
      %% % Number itself
  2. Part time module described method:

    time.time() Get the current timestamp
    time.sleep() Sleep (delay)
    time.localtime() Converting the time stamp to the structured
    time.mktime() The time stamp of the conversion structure
    time.strftime() Converting the format of the time period of the structure
    time.strptime() Converting the formatted time is structured time
    • time.time()

      • Function definition:time()
      • Function Description: Get the current timestamp from 1970-01-01 00:00:00 to pass the time now, in seconds, the result is a floating-point type
      import time
      
      print(time.time())
      
      运行结果:
      1569505356.1715019
      
    • time.sleep()

      • Function definition:sleep(seconds)
      • Function Description: second parameter will be performed for a few seconds delay, may be sub-second-level float
      import time
      
      print(1)
      time.sleep(10)
      print(2)
      
      运行结果:
      1
      2  # 相隔10S 
      
    • time.localtime()

      • Function definition:localtime([seconds])
      • The function returns:(tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
      • Function Description: timestamp parameter, is converted to a time stamp showing time tuples local time, when secondsthere is no incoming, convert the current timestamp
      import time
      
      print(time.localtime())
      
      运行结果:
      time.struct_time(tm_year=2019, tm_mon=9, tm_mday=26, tm_hour=22, tm_min=2, tm_sec=38, tm_wday=3, tm_yday=269, tm_isdst=0)
      
      • Return value Value:

        • The return value can be indexed by the value
        import time
        
        print(time.localtime()[0])
        
        运行结果:
        2019
        
        • The return value by the value of keyword
        import time
        
        print(time.localtime().tm_year)
        
        运行结果:
        2019
        
    • time.mktime()

      • Function definition:mktime(p_tuple)
      • Function: a structured time parameter tuples, the tuple structure of time stamp is converted to
      import time
      
      t = time.localtime()
      print(time.mktime(t))
      
      运行结果:
      1569506956.0
      
    • time.strftime()

      • Function definition:strftime(format, p_tuple=None)
      • Function Description: The first argument is a format specification, the structure of the second parameter is time-tuple, the tuple structured into a string of time, if the time when the tuple does not exist, localtime()the current time to return a string
      import time
      
      t = time.localtime()
      print(time.strftime("%Y-%m-%d %H:%M:%S", t))
      
      运行结果:
      2019-09-26 22:19:30
      
    • time.strptime()

      • Function definition:strptime(string, format)
      • Function Description: The first parameter is a time string, the second parameter is standardized format, according to the format specification string parsed into time tuple
      import time
      
      print(time.strptime("2019-09-26 22:19:30", "%Y-%m-%d %H:%M:%S"))
      
      运行结果:
      time.struct_time(tm_year=2019, tm_mon=9, tm_mday=26, tm_hour=22, tm_min=19, tm_sec=30, tm_wday=3, tm_yday=269, tm_isdst=-1)
      
  • Calculate the time difference

    import time
    
    time_msg = input("请输入时间:")
    def time_difference(args):
        tid = time.time() - time.mktime(time.strptime(args, "%Y-%m-%d %H:%M:%S"))
        return time.localtime(tid)
    
    t = time_difference(time_msg)
    print(f"过去了{t.tm_year-1970}年{t.tm_mon-1}月{t.tm_mday-1}天{t.tm_hour}小时{t.tm_min}分{t.tm_sec}秒")
    
    运行结果:
    请输入时间:2019-01-01 00:00:00
    过去了0年8月26天6小时39分17秒
    

(Ii) datetime module

  • datetime module is also a time module, function module stronger than time
  1. datatime class section datatime module Method description:

    datetime() Gets the specified time
    datetime.now() Get the current time
    datetime.timestamp() The conversion time timestamp object
    datetime.fromtimestamp() Converting the timestamp time target
    datetime.strftime() The conversion time object to a string
    datetime.strptime() Converts a string to an object time
    • datetime()

      • Function definition:datetime(year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ...)
      • Function Description: Incoming year, month, day, hour, minute, second, microsecond, time zone, fold (unknown parameters, adding 3.6), returns a time target
      from datetime import datetime
      
      print(datetime(2019,9,27))
      print(type(datetime(2019,9,27)))
      
      运行结果:
      2019-09-27 00:00:00
      <class 'datetime.datetime'>  # 对象类型
      
    • datetime.now()

      • Function definition:now(tz=None)
      • Function Description: Parameter time zone, create a time object through the datetime object, you can select the time zone information
      from datetime import datetime
      
      print(datetime.now())
      print(type(datetime.now()))
      
      运行结果:
      2019-09-27 14:06:10.948891
      <class 'datetime.datetime'>
      
    • datetime.timestamp()

      • Function definition:timestamp(obj)
      • Description Function: Date object parameters, the object conversion time stamp
      from datetime import datetime
      
      print(datetime.timestamp(datetime.now()))
      print(type(datetime.timestamp(datetime.now())))
      
      运行结果:
      1569565460.237563
      <class 'float'>
      
    • datetime.fromtimestamp()

      • Function definition:fromtimestamp(t, tz=None)
      • Function Description: The first parameter is a time stamp, the second parameter time zone, the incoming time stamp is converted to the object
      from datetime import datetime
      
      print(datetime.fromtimestamp(0))
      print(type(datetime.fromtimestamp(0)))
      
      运行结果:
      1970-01-01 08:00:00
      <class 'datetime.datetime'>
      
    • datetime.strftime()

      • Function definition:strftime(obj, format)
      • Function Description: The first parameter is the target time, the second parameter is standardized format, according to the format specification string object conversion time
      from datetime import datetime
      
      print(datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S"))
      print(type(datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")))
      
      运行结果:
      2019-09-27 14:35:37
      <class 'str'>
      
    • datetime.strptime()

      • Function definition:strptime(date_string, format)
      • Function Description: The first parameter is a time string, the second parameter is the format specification, the parse time strings formatted object according to the time specification
      from datetime import datetime
      
      print(datetime.strptime("2019-09-27 14:35:37", "%Y-%m-%d %H:%M:%S"))
      print(type(datetime.strptime("2019-09-27 14:35:37", "%Y-%m-%d %H:%M:%S")))
      
      运行结果:
      2019-09-27 14:35:37
      <class 'datetime.datetime'>
      
  2. timedelta class section datatime module Method description:

    • delta h ()

      • Function definition:timedelta(days: float = ..., seconds: float = ..., microseconds: float = ..., milliseconds: float = ..., minutes: float = ..., hours: float = ..., weeks: float = ..., *, fold: int = ...)
      • Function: a function of time for scaling object, fill in the corresponding keyword parameters-time value
      from datetime import datetime, timedelta
      
      print(datetime(2019, 1, 2))
      print(datetime(2019, 1, 2) - timedelta(days=1))
      
      运行结果:
      2019-01-02 00:00:00
      2019-01-01 00:00:00
      

(C) random module

  • random is a random module, any random circumstances require random module help complete
  1. random module section describes the method:

    random.random() Generating a random decimal between 0 and 1
    random.randint() Randomly generated numbers
    random.randrange () Generating a random number (step size can be set)
    random.choice() Acquiring a random element from one iteration object
    random.choices() Acquiring a random element from a plurality of objects may be iterative, there is repeated
    random.sample() Acquiring a random element from a plurality of objects may be iterative, and does not repeat
    rendom.shuffle () Random scrambled
    • random.random()

      • Function definition:random()
      • Function Description: generating a random decimal between 0 and 1
      import random
      
      print(random.random())
      
      运行结果:
      0.8988729646775544
      
    • random.randint()

      • Function definition:randint(a, b)
      • Function Description: generating a random number between a to b
      import random
      
      print(random.randint(1, 10))
      
      运行结果:
      9
      
    • random.randrange ()

      • Function definition:randrange(start, stop=None, step=1, _int=int)
      • Function Description: generating within a range from the start to the end of a random number, the step size may be set, if the fill end position from zero by default, if fill step, the default is 1
      import random
      
      print(random.randrange(5))  # 从0到5随机生成
      print(random.randrange(1, 10))  # 从1到10随机生成
      print(random.randrange(1, 10, 2))  # 从1到10
      
      运行结果:
      4
      3
      9
      
    • random.choice()

      • Function definition:choice(seq)
      • Function: Select an element from a non-empty sequence random
      import random
      
      print(random.choice(["a", "b", "c"])
      
      运行结果:
      b
      
    • random.choices()

      • Function definition:choices(population, weights=None, *, cum_weights=None, k=1)
      • 函数说明:从非空序列中随机选择k个元素,会有重复选择的情况,以列表的形式返回
      import random
      
      print(random.choices(["a", "b", "c"], k=3))
      
      运行结果:
      ['b', 'b', 'a']
      
    • random.sample()

      • 函数定义:sample(population, k)
      • 函数说明:随机从非空序列中选择k个元素,不会重复选择,以列表的形式返回
      import random
      
      print(random.sample(["a", "b", "c"], k=3))
      
      运行结果:
      ['c', 'b', 'a']
      
    • rendom.shuffle()

      • 函数定义:shuffle(x, random=None)
      • 函数说明:将参数重新洗牌,结果返回None
      import random
      
      lst = [1, 2, 3, 4, 5]
      random.shuffle(lst)
      print(lst)
      
      运行结果:
      [2, 3, 5, 4, 1]
      

(四)os模块

  • os模块中的内容全部与操作系统有关
  1. os模块部分方法介绍:

    os.makedirs('dirname1/dirname2') 递归创建目录**
    os.removedirs('dirname1') 递归删除目录
    os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir(path) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove() 删除一个文件
    os.rename("oldname","newname") 重命名文件/目录
    os.stat('path/filename') 获取文件/目录信息
    os.system("bash command") 运行shell命令,直接显示
    os.popen("bash command").read() 运行shell命令,获取执行结果
    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
    os.path.abspath(path) 返回path规范化的绝对路径
    os.path.split(path) 将path分割成目录和文件名二元组返回
    os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
    os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
    os.path.isabs(path) 如果path是绝对路径,返回True
    os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
    os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
    os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间
    os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
    os.path.getsize(path) 返回path的大小
    • 重点介绍常用15个方法

    • os.makedirs('dirname1/dirname2')

      • 函数定义:makedirs(dirname)
      • 函数说明:递归创建文件夹
      import os
      
      os.makedirs("dir1/dir2/dir3")  # 在当前目录递归创建文件夹
      
      运行结果:
      # 创建三层文件夹
      ◥dir1
         ◥dir2
             ◥dir3
      
    • os.removedirs('dirname1')

      • 函数定义:removedirs(dirname)
      • 函数说明:若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
      import os
      
      os.removedirs("dir1/dir2/dir3")
      
      运行结果:
      # 先判断dir3目录是否为空,若为空则删除,再一次向上判断,递归删除文件夹
      
    • os.mkdir('dirname')

      • 函数定义:mkdir(dirname)
      • 函数说明:创建单级目录
      import os
      
      os.mkdir("dir1")
      
      运行结果:
      # 创建dir1文件夹
      
    • os.rmdir('dirname')

      • 函数定义:rmdir(dirname)
      • 函数说明:删除单级目录,若目录不存在或不为空报错
      import os
      
      os.rmdir("dir1")
      
      运行结果:
      # 若dir1为空,删除dir1文件夹
      
    • os.listdir(path)

      • 函数定义:listdir(path)
      • 函数说明:返回该路径下的所有文件夹和文件,以列表的形式
      import os
      
      print(os.listdir("D:\dir"))
      
      运行结果:
      ['dir1', 'dir2', 'dir3']
      
    • os.remove()

      • 函数定义:remove(filename)
      • 函数说明:删除文件
      import os
      
      os.remove("text.py")
      
      运行结果:
      # 直接删除"text.py"文件
      
    • os.rename("oldname","newname")

      • 函数定义:rename(oldname, newname)
      • 函数说明:重命名,第一个参数为旧文件名,第二个参数为新文件名
      import os
      
      os.rename("text1.py", "text2.py")
      
      运行结果:
      # 将文件名"text1.py"改为"text2.py"
      
    • os.getcwd()

      • 函数定义:getcwd(*args, **kwargs)
      • 函数说明:返回当前文件的工作路径,以Unicode字符串的形式(若被当作模块导入,则返回的是导入文件的工作路径)
      import os
      
      print(os.getcwd("text.py"))
      
      运行结果:
      D:\text.py
      
    • os.path.abspath(path)

      • 函数定义:abspath(path)
      • 函数说明:返回当文件的绝对路径
      import os
      
      print(os.path.abspath("text.py"))
      
      运行结果:
      D:\text.py
      
    • os.path.dirname(path)

      • 函数定义:dirname(path)
      • 函数说明:返回文件的目录
      import os
      
      path = r"D:\dir\dir1\name.py"
      print(os.path.dirname(path))
      
      运行结果:
      D:\dir\dir1
      
    • os.path.basename(path)

      • 函数定义:basename(path)
      • 函数说明:返回文件名
      import os
      
      path = r"D:\dir\dir1\name.py"
      print(os.path.basename(path))
      
      运行结果:
      name.py
      
    • os.path.isfile(path)

      • 函数定义:isfile(path)
      • 函数说明:判断路径是否是一个文件
      import os
      
      path = r"D:\dir\dir1\name.py"
      print(os.path.isfile(path))
      
      运行结果:
      True
      
    • os.path.isdir(path)

      • 函数定义:isdir(path)
      • 函数说明:判断路径是否是一个文件夹
      import os
      
      path = r"D:\dir\dir1"
      print(os.path.isdir(path))
      
      运行结果:
      True
      
    • os.path.join(path1[, path2[, ...]])

      • 函数定义:join(path, *paths)
      • 函数说明:将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
      import os
      
      path = r"D:\dir"
      print(os.path.join(path, "dir1", "text.py"))
      print(os.path.join("text.py", path, "dir1", "text.py"))
      
      运行结果:
      D:\dir\dir1\text.py
      D:\dir\dir1\text.py
      
    • os.path.getsize(path)

      • 函数定义:getsize(filename)
      • 函数说明:返回文件的大小
      import os
      
      path = r"D:\dir\dir1\name.py"
      print(os.path.getsize(path))
      
      运行结果:
      7971
      

(五)sys模块

  • sys模块是与python解释器交互的一个接口
  1. sys模块部分方法介绍:

    sys.argv 命令行参数List,第一个元素是程序本身路径
    sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)
    sys.version 获取Python解释程序的版本信息
    sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform 返回操作系统平台名称
    sys.modules 获取所有的模块
    • sys.path

      • 方法说明:返回模块的搜索路径,以列表的形式,需要导入自定义模块时,向sys.path中添加路径
      import sys
      
      print(sys.path)
      
      运行结果:
      ['D:\\python_S26\\day15', 'D:\\python_S26', 'D:\\Software\\Pycharm\\pycharm\\PyCharm 2019.2.1\\helpers\\pycharm_display', 'C:\\Python3.6.8\\python36.zip', 'C:\\Python3.6.8\\DLLs', 'C:\\Python3.6.8\\lib', 'C:\\Python3.6.8', 'C:\\Python3.6.8\\lib\\site-packages', 'D:\\Software\\Pycharm\\pycharm\\PyCharm 2019.2.1\\helpers\\pycharm_matplotlib_backend']
      

(六)functools模块

  • funtools模块针对于一些函数的操作
  1. 之前介绍过的reduce()函数,用于累计算

    from functools import reduce
    
    print(reduce(lambda x, y: x * y, [1, 2, 3, 4, 5]))
    print(reduce(lambda x, y: x * y, [1, 2, 3, 4, 5], 5))
    print(reduce(lambda x, y: x * y, [], 5))
    
    运行结果:
    120
    600
    5
    
  2. wraps

    • 用于修改装饰器内层函数的函数名

    • 我们在执行被装饰器装饰过的函数时,其实真正执行的是装饰器内部的inner函数,我们通过__name__方法可查看函数调用真正调用的函数名

      def wrapper(fn):
         def inner(*args, **kwargs):
             print("扩展内容")
             ret = fn(*args, **kwargs)
             print("扩展内容")
             return ret
         return inner
      
      @wrapper
      def target_func():
         print("目标函数")
      
      print(target_func.__name__)
      
      运行结果:
      inner
      
    • 但对于调用方而言,会对函数产生疑问,所以使用warps可以修改内层inner函数的函数名

      from functools import wraps
      
      def wrapper(fn):
         @wraps(fn)  # 装饰内层函数
         def inner(*args, **kwargs):
             print("扩展内容")
             ret = fn(*args, **kwargs)
             print("扩展内容")
             return ret
         return inner
      
      @wrapper
      def target_func():
         print("目标函数")
      
      print(target_func.__name__)
      
      运行结果:
      target_func
      

Guess you like

Origin www.cnblogs.com/tianlangdada/p/11621367.html