跟着ALEX 学python day5 模块

文档内容学习于

http://www.cnblogs.com/xiaozhiqi/ 

 

 

模块

1.模块:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py,对应的模块名:test)。

   包(package): 用来从逻辑上组织模块的,本质就是一个目录,(必须带有一个_init_.py的文件),也可以用import的方式 导入。

2.导入方法:

import  module_name 

导入多个模块 用,隔开

import  module_name, module_name2 

[root@localhost day5]# ls
module_test.py  __pycache__  use.py
[root@localhost day5]# cat module_test.py 
#!/usr/bin/env  python3

name =  ("dragon")
name2 =  ("zhuzhu")

def say():
	print  (name2)



[root@localhost day5]# cat use.py 
#!/usr/bin/env  python3

import  module_test
print (module_test.name)

module_test.say()


[root@localhost day5]# ./use.py 
dragon
zhuzhu

 

导入一个模块中所有的函数,这是你导入的其实是这个文件中的所有  代码。并不是 导入了这个模块

需慎用

from   module_test  import  M1           #导入模块中的函数
from module_test import M1,M2,M3 #导入模块中的多个函数
from module_test import * #导入模块中的所有函数

 

直接导入模块中的所有函数的话。 直接调模块是调不通的。  

[root@master day5]# cat use.py 
#!/usr/bin/env  python3
from  module_test   import  *  
module_test.say()

[root@master day5]# ./use.py 
Traceback (most recent call last):
  File "./use.py", line 4, in <module>
    print (module_test.name)
NameError: name 'module_test' is not defined

 

在这种方式下调用,就像这个文件自身调函数一样 ,所有这种方法其实不推荐,因为有可能会和本生文件中函数名相冲突。

[root@master day5]# cat module_test.py 
#!/usr/bin/env

name =  ("dragon")
name2 =  ("zhuzhu")

def say():
        print  (name2)
[root@master day5]# cat use.py #!/usr/bin/env python3 from module_test import * say()
[root@master day5]# ./use.py zhuzhu

 

 

 

as    函数别名

调取另一个模块中的函数, 并给他取别名

[root@master day5]# cat use.py 
#!/usr/bin/env  python3

#import  module_test
#  print (module_test.name)
from  module_test   import  say as say_module               # 给say这个函数取别名 

say_module()

 

 

import的本质

导入模块的本质就是把python文件解释一遍。

导入包的本质就是执行该包下的_init_.py文件

 

那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path

>>> import sys
>>> print(sys.path)
['', '/home/tomcat/.pyenv/versions/3.5.1/lib/python35.zip',
'/home/tomcat/.pyenv/versions/3.5.1/lib/python3.5',
'/home/tomcat/.pyenv/versions/3.5.1/lib/python3.5/plat-linux',
'/home/tomcat/.pyenv/versions/3.5.1/lib/python3.5/lib-dynload',
'/home/tomcat/.pyenv/versions/3.5.1/lib/python3.5/site-packages']

 

如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。

import sys
import os
project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_path) 

 

 

 

 

模块的分类:

a: 标准库

自带的模块

1.time和datetime

有几类时间表示的方式 1. 时间戳  2.格式化的时间字符串    3. 元组(struct_time) 共就九个元素

 

time 模块

help(time)       #查看所有方法

 

time.time()

返回的时间戳,  1970年到现在的秒

>>> time.time()
1564020387.0246904

 

time.sleep()

暂停时间,暂停10秒

>>> time.sleep(10)
>>>

 

 

 time.gmtime()

以元组的形式展现。是UTC形式的, 就是标准时。 和国内的时间不一样。 中国在东8区(UTC+8)。

>>> time.gmtime()
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=25, tm_hour=3, tm_min=18, tm_sec=43, tm_wday=3, tm_yday=206, tm_isdst=0)
>>>

 

也可以传时间戳,根据时间戳转换成UTC的时间

>>> time.gmtime(955645646)
time.struct_time(tm_year=2000, tm_mon=4, tm_mday=13, tm_hour=17, tm_min=7, tm_sec=26, tm_wday=3, tm_yday=104, tm_isdst=0)

 

也可以取变量

>>> a = time.gmtime()
>>> print (a.tm_year)
2019

 

 

 

time.localtime()

这个就是本地的时候

>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=25, tm_hour=11, tm_min=33, tm_sec=2, tm_wday=3, tm_yday=206, tm_isdst=0)

 也可以传时间戳,根据时间戳转换成当地的时间

>>> time.localtime(955645646)
time.struct_time(tm_year=2000, tm_mon=4, tm_mday=14, tm_hour=1, tm_min=7, tm_sec=26, tm_wday=4, tm_yday=105, tm_isdst=0)

 

 

 

mktime  
将列表格式的时间。 转换成时间戳
>>> a = time.gmtime()
>>> time.mktime(a)
1564014091.0

 

 

time.strftime
格式化时间

help(time.strftime)
Help on built-in function strftime in module time:

strftime(...)
    strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.

    Commonly used format codes:

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.

    Other codes may be available on your platform.  See documentation for
    the C library strftime function.

 


 

格式化的字符串

>>> time.strftime("%Y-%m-%d:%H:%M:%S",a)            # a = time.gmtime()     a 是变量
'2019-07-25:08:21:31'

 

time.strptime
反向转换,格式化的字符串 转成时间戳
>>> help(time.strptime)
Help on built-in function strptime in module time:

strptime(...)
    strptime(string, format) -> struct_time

    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).

    Commonly used format codes:

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.

    Other codes may be available on your platform.  See documentation for
    the C library strftime function.

 



 

先写日期,在写格式,在位置上必须一一对应。

>>> time.strptime("2019-07-25:08:21:31","%Y-%m-%d:%H:%M:%S")
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=25, tm_hour=8, tm_min=21, tm_sec=31, tm_wday=3, tm_yday=206, tm_isdst=-1)

 

 

 这边其实就相当于 一一 赋值

%Y = tm_year
%m = tm_mon
%d = tm_mday
%H = tm_hour
%M = tm_min
%S = tm_sec  

 

 

 asctime 
元组转字符串。 如果不传默认就是当前时间的元组

>>> time.asctime()
'Thu Jul 25 19:53:07 2019'

 

 

ctime
时间戳转成字符串。如果不传默认就是当前时间的时间戳
>>> time.ctime()
'Thu Jul 25 19:58:02 2019'

 

 

 

 

 

 datetime

 基于 time 封装的一个模块

获取当前的时间

>>> print(datetime.datetime.now())
2019-07-25 20:05:57.827178

 

datetime.timedelta参数
>>> print(datetime.datetime.now() + datetime.timedelta(3))                           #3天后的时间。datetime.timedelta这个参数一定和datetime.datetime这个参数一起使用
2019-07-28 20:08:42.490283
>>> print(datetime.datetime.now() + datetime.timedelta(-3))                          #3天前的时间。datetime.timedelta这个参数一定和datetime.datetime这个参数一起使用
2019-07-22 20:09:10.408564
>>> print(datetime.datetime.now() + datetime.timedelta(hours=3))                     #3小时后
2019-07-25 23:12:08.577534
>>> print(datetime.datetime.now() + datetime.timedelta(hours=-3))                    #3小时前  
2019-07-25 17:12:12.089382
>>> print(datetime.datetime.now() + datetime.timedelta(minutes=3))                   #3分钟后
2019-07-25 20:15:25.246800
>>> print(datetime.datetime.now() + datetime.timedelta(minutes=-3))                  #3分钟前
2019-07-25 20:09:27.382501

 

 

replace  替换时间
>>> print (datetime.datetime.now())
2019-07-25 20:10:07.796370
>>> c = datetime.datetime.now()
>>> print (c.replace(minute=10,hour=2))                      # 将小时和  分钟替换了
2019-07-25 02:10:19.484883

 

 

random

随机 生成浮点数。

>>> random.random()
0.26248176326423267

 

随机生成整数

>>> random.randint(1,3)
2
>>> random.randint(1,3)
2
>>> random.randint(1,3)
1

 

随机抽取元素

>>> random.choice('hello')
'h'
>>> random.choice('hello')
'o'
>>> random.choice([1,2,3,8])
1
>>> random.choice([1,2,3,8])
3

 

uniform

在  浮点数的基础上加了区间。

>>> random.uniform(1,3)
2.99240011573443
>>> random.uniform(1,3)
1.9169214499374079
>>> random.uniform(1,3)
2.136544854353717
>>> random.uniform(1,3)
2.6272767080756982

 

洗牌功能, 就是将一个列表里面的数字,全部打乱。

>>> l = [1,2,3,4,5,6,7]
>>> l
[1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(l)
>>> l
[4, 2, 1, 6, 5, 3, 7]

 

 

可以用在验证码的功能 

[root@localhost day5]# cat checkcode.py 
#!/usr/bin/env  python3

import   random
checkcode = ''

for i in range(4):
    current = random.randint(1,9)
    checkcode = checkcode + str(current)

print (checkcode)

[root@localhost day5]# ./checkcode.py 
8155
[root@localhost day5]# ./checkcode.py 
5592
[root@localhost day5]# ./checkcode.py 
5976
[root@localhost day5]# ./checkcode.py 
7876

 

 

数字和 字母结合的验证码

[root@localhost day5]# cat checkcode.py 
#!/usr/bin/env  python3


# Author ricky

import   random
checkcode = ''

for i in range(4):
    currrent = random.randrange(0,4)
    if currrent == i:                                             # 转换字母   判断如果  是 0-4 之间
        tmp = chr(random.randint(65,90))                          # chr函数,可以将数字转换成字母。 65到90是 对应ASCII  A---Z
    else:                                                         # 转换数字。 如果不在0-4之间。
        tmp = random.randint(0,9)                                              
    checkcode =checkcode + str(tmp)

print (checkcode)

[root@localhost day5]# ./checkcode.py 
811T
[root@localhost day5]# ./checkcode.py 
513T
[root@localhost day5]# ./checkcode.py 
8407
[root@localhost day5]# ./checkcode.py 
8613
[root@localhost day5]# ./checkcode.py 
E306

 

 

 OS 模块

可以针对文件进行操作

getcwd   类似于  linux的 pwd

>>> import os
>>> os.getcwd()
'C:\\Users\\1040323'

 

 os.chdir

 切换路径

>>> os.chdir("C:\\Users")
>>> os.getcwd()
'C:\\Users'

 

>>> os.curdir                                       # 返回的是当前目录
'.'
>>> os.pardir                                       #  获取当前目录的父目录
'..'

 

创建目录

[root@localhost day5]# cat module.py 
#!/usr/bin/env python3

import  os
os.mkdir("/home/a")
[root@localhost day5]
# ./module.py [root@localhost day5]# ll /home/ total 0 drwxr-xr-x 2 root root 6 Jul 26 03:33 a drwxr-xr-x 3 root root 63 Jul 3 08:29 awx drwxr-xr-x 5 root root 146 Jul 13 08:03 python

 

 

makedirs  

相当于 linux的 mkdir -p

windows的目录格式

>>> os.makedirs(r"D:\a\b\c\e")           

 

 创建完了

 

linux的 目录格式

[root@localhost day5]# cat   module.py 
#!/usr/bin/env python3


import  os

os.makedirs("/home/a/b/c/d")
[root@localhost day5]# ./module.py 

创建完了。

 

 

 删除目录

[root@localhost day5]# cat module.py 
#!/usr/bin/env python3

import  os
os.rmdir("/home/a/b/c/d")
[root@localhost day5]
# ./module.py [root@localhost day5]# tree /home/a/ /home/a/ └── b └── c

 

清除空目录

os.removedirs("/home/a/b/c/d")                                # 若目录为空,则删除。并递归到上一级目录。如若也给空,则删除。一次类推。

 

 就是如果他的上级目录也会也空的话。  会一起删除 ,“a/b/c/d”  都是 空目录的话。  会一起删除。

 a  已经没了

 

 

 

 列出目录

>>> os.listdir(".")
['1040323', 'A', 'Administrator', 'All Users', 'Default', 'Default User', 'defaultuser0', 'desktop.ini', 'Public']

 

删除文件

>>> os.remove("1.txt")

 

修改文件名

>>> os.rename("old.txt","new.txt")

 

查看文件属性

>>> os.stat("new.txt")
os.stat_result(st_mode=33206, st_ino=4785074604297078, st_dev=1883298865, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1564196833, st_mtime=1564196833, st_ctime=1564196828)

 

 

 os.sep

输出操作系统特定的路径分隔符。win下是“\\”  linux下是"/"

windows

>>> os.sep
'\\'

 

linux

[root@localhost day5]# cat module.py 
#!/usr/bin/env python3

import  os
print ( os.sep)
[root@localhost day5]
# ./module.py /

 

 

os.lineseq 

输出当前平台使用的行终止符,换行符。

wins

>>> os.linesep
'\r\n

 

linux

>>> os.linesep
'\n'

 

 

os.pathsep 输出分割文件路劲的字符

windows

>>> os.pathsep
';'

 

 

linux

>>> os.pathsep
':'

 

 os.name  查看系统平台

windows

>>> os.name
'nt'
>>>

 

linux

>>> os.name
'posix

 

os.system

执行系统命令

>>> os.system('ip add')
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:29:cb:37 brd ff:ff:ff:ff:ff:ff
    inet 192.168.249.152/24 brd 192.168.249.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe29:cb37/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
0
>>> os.system('ls')    
anaconda-ks.cfg  def-ns-admin.conf  python
0

 

获取系统环境变量

>>> os.environ

 

os.path.abspath

返回绝对路劲 。用于加载自定义模块的时候使用

>>> os.path.abspath('./anaconda-ks.cfg')           
'/root/anaconda-ks.cfg'

 

os.path.split   将文件和 目录结构分开 ,二元组形式
>>> os.path.split('/home/yaml/deploy-damon.yaml')                       
('/home/yaml', 'deploy-damon.yaml')

 

>>> os.path.dirname('/home/yaml/deploy-damon.yaml')                 #  只打印目录  
'/home/yaml'
>>> os.path.basename('/home/yaml/deploy-damon.yaml')                #   只打印文件
'deploy-damon.yaml'
>>> os.path.exists('/home/a/')    # 用来判断 路径是否存在
True
>>> os.path.exists('/home/g/')
False
>>> os.path.isabs('/home') # 判断是否是绝对路劲
True
>>> os.path.isabs('./')   
False
>>> os.path.isdir('/home/a')   # 判断是是否是目录
True
>>> os.path.isfile('/home/yaml/deploy-sa.yaml') # 判断是否是文件
True
>>> os.path.join('/home','yaml') # 将多个路径组合
'/home/yaml'
>>> os.path.getatime('/home/yaml/deploy-sa.yaml') # 获取最后的存取时间
1545720743.1583107
>>> os.path.getmtime('/home/yaml/deploy-sa.yaml') # 获取最后的修改时间
1545720741.7793107

 

 shutil 模块

主要作用与拷贝文件用的

参考:
https://www.cnblogs.com/xiangsikai/p/7787101.html

 

1.shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。

import shutil

f1 = open("1.txt",encoding="utf-8")

f2 = open("2.txt","w",encoding="utf-8")

shutil.copyfileobj(f1,f2)

 

 sh2.shutil.copyfile(文件1,文件2):不用打开文件,直接用文件名进行覆盖copy。util模块

 2.shutil.copyfile(文件1,文件2):不用打开文件,直接用文件名进行覆盖copy。

 

import shutil

shutil.copyfile("1.txt","3.txt")

 

 3.shutil.copymode(文件1,文件2):之拷贝权限,内容组,用户,均不变。

 

 

 

b:  开源模块

c:  自定义模块

 

转载于:https://www.cnblogs.com/rockyricky/p/11171784.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值