python笔记-1(import导入、time/datetime/random/os/sys模块)

python笔记-6(import导入、time/datetime/random/os/sys模块)

 

一、了解模块导入的基本知识

此部分此处不展开细说import导入,仅写几个点目前的认知即可。其它内容待日后有深入理解了再来细说

1、import可以导入的两种不同的内容

1.1 *.py文件结尾的文件

1.2 package文件

package和文件夹图标类似,package中又__init__.py的文件

2、模块导入的几种导入方式

2.1 from xxx import xxx as xxx 

2.2 from xxx import xxx as xxx as xxx 别名

2.3 import xxx

3、import 和 from xxx import 的区别

import xxx的本质是执行py文件,import package是执行__init__.py

from xxx import xxx 的本质是将xxx部分的内容复制到本地,进行调用。

4、需要重点掌握给sys(python解释器)添加环境变量的方法

4.1 os.path.abs(文件)

4.2 os.path.dirname(绝对路径)

4.3 sys.path.append()/sys.path.insert()

 

二、time模块-->时间模块

1、要熟悉时间的三种表示方式

1.1、格式化字符串 ‘2018-2-1 11:11:12’

   此处的格式我们可以随意去自定义,其实质是按照固定的格式,从时间的9元组中获取需要的变量,根据定义的格式输出字符串

1.2、时间戳

一串数字,用来表示和1970年的时间间隔,单位为s。

注意点:一个时间戳所换算成的时间九元组是固定的。但是,根据时区的不同,python会进行相应的转换,转换成当地的时间。在熟悉了这个情况后,在后面的时间表示方式的转换中,要明确我要转换成的是标准时间还是当地时间。

1.3、元组 struct_time 9个元素

year (including century, e.g. 1998) 

month (1-12)

day (1-31)

hours (0-23)

minutes (0-59)

seconds (0-59)

weekday (0-6, Monday is 0)一周第几天注意星期一是第0天

Julian day (day in the year, 1-366)一年第几天,从1开始计

DST (Daylight Savings Time) flag (-1, 0 or 1)是否是夏令时,0代表不是,1代表是

例子

?
1
time.struct_time(tm_year = 2017 , tm_mon = 12 , tm_mday = 31 , tm_hour = 23 , tm_min = 27 , tm_sec = 2 , tm_wday = 6 , tm_yday = 365 , tm_isdst = 0 )

4、time模块的几个变量

4.1 timezone 

表示世界标准时间utc和本地时间的差值,单位为秒。中国的时区比时间标准时间快8小时。

utc - (utc+8)

?
1
2
3
4
5
6
7
>>> time.timezone
 
- 28800
 
>>> 28800 / 3600
 
8.0

4.2 altzone

UTC和本地夏令时直接的差值,单位为s 我们不使用夏令时,所以此处不做深究,了解即可

?
1
2
3
>>> time.altzone #夏令时和utc的时间差值
 
- 32400

4.3 time.daylight

是否使用了夏令时,0为不使用

?
1
2
3
>>> time.daylight 是否使用了夏令时
 
0

5、time的函数

5.1 time.time() 获取时间戳

此处获取的时间戳为utc标准时间与1970的时间间隔。

5.2 time.sleep()

延时多少秒,单位为秒

5.3 time.gmtime() 

gmtime() -- convert seconds since Epoch to UTC tuple

将时间戳转换为utc时间

5.4 time.localtime()

localtime() -- convert seconds since Epoch to local time tuple

将时间戳转换成本地时间

?
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> time.time()
 
1520614121.487381
 
>>> time.gmtime(time.time())
 
time.struct_time(tm_year = 2018 , tm_mon = 3 , tm_mday = 9 , tm_hour = 16 , tm_min = 49 , tm_sec = 4 , tm_wday = 4 , tm_yday = 68 , tm_isdst = 0 )
 
>>> time.localtime(time.time())
 
time.struct_time(tm_year = 2018 , tm_mon = 3 , tm_mday = 10 , tm_hour = 0 , tm_min = 49 , tm_sec = 14 , tm_wday = 5 , tm_yday = 69 , tm_isdst = 0 )
 
>>>

此程序的说明:注意time.gmtime()与time.localtime()的对比

Time.time()为获取一个时间戳,需要明确 时间戳其实就是utc与1970的时间差

Time.gmtime(time.time())将时间戳转换为utc九元组

Time.localtime(time.time())将时间戳转换为本地时间的九元组,实际就是转换为标准的九元组后,根据timezone进行换算的

5.5 如何取用时间struct_time-9元组的值

时间元组赋值给变量,变量用.来引用

?
1
2
3
4
5
6
7
8
9
10
11
import time
 
x = time.gmtime()
 
print (x)
 
print (x.tm_year,x.tm_yday)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
time.struct_time(tm_year = 2018 , tm_mon = 2 , tm_mday = 26 , tm_hour = 17 , tm_min = 22 , tm_sec = 23 , tm_wday = 0 , tm_yday = 57 , tm_isdst = 0 )
 
2018 57

5.6  strftime() 

将元组转换为标准格式输出

这里的元组默认为localtime,如果给出元组,则从元组中取值

Time.strftime(格式,元组)

?
1
2
3
>>> time.strftime( '%Y %m %d %X' )
 
'2018 02 10 01:21:43'

 

5.7 strptime()

将文本格式转换为元组

Time.strptime(文本,格式)

?
1
2
3
4
5
>>> time.strptime( '2018 02 10 01:21:43' , '%Y %m %d %X' )
 
time.struct_time(tm_year = 2018 , tm_mon = 2 , tm_mday = 10 , tm_hour = 1 , tm_min = 21 , tm_sec = 43 , tm_wday = 5 , tm_yday = 41 , tm_isdst = - 1 )
 
>>>

注意:tm_isdst这个部分,转换之后夏令时为-1

5.8 Time.ctime(时间戳)

会转换为本地时区的 文本形式时间

?
1
2
3
>>> time.ctime(time.time()) #默认传入time.time()
 
'Sat Mar 10 01:31:45 2018'                                         

5.9 Time.asctime(time.localtime())默认传入localtime

从元组取值转换成固定的格式输出,和strftime类似

?
1
2
3
4
5
6
7
8
9
10
11
>>> time.asctime(time.gmtime())
 
'Fri Mar  9 17:33:26 2018'
 
>>> time.asctime(time.localtime())
 
'Sat Mar 10 01:33:32 2018'
 
>>> time.asctime()
 
'Sat Mar 10 01:33:39 2018'

5.10 time.mktime() -- convert local time tuple to seconds since Epoch

本地的时间的元组转换为时间戳

Localtime->转换为标准的时间戳->utc->local

?
1
2
3
4
5
>>> time.localtime(time.mktime(time.localtime()))
 
time.struct_time(tm_year = 2018 , tm_mon = 3 , tm_mday = 10 , tm_hour = 1 , tm_min = 37 , tm_sec = 31 , tm_wday = 5 , tm_yday = 69 , tm_isdst = 0 )
 
>>>

5.11 tzset() -- change the local timezone

改变timezone变量,调整时区,一般不使用

 

三、datetime模块的使用

1、获取当前时间的方法 datetime.datetime.now()

以字符串形式输出

?
1
2
3
print (datetime.datetime.now())当前时间
 
2018 - 01 - 04 02 : 11 : 37.867479

2、知道datetime.datetime.now()的类型

?
1
< class 'datetime.datetime' >

3、定义输出格式 与strftime结合

?
1
2
3
4
5
6
7
print (datetime.datetime.now())
 
print (datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ))<br> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 
2018 - 03 - 10 09 : 46 : 28.106559
 
2018 - 03 - 10 09 : 46 : 28

4、str格式时间转成datetime.datetime类

?
1
2
3
4
5
6
7
8
d1 = datetime.datetime.strptime( '2015-03-05 17:41:20' , '%Y-%m-%d %H:%M:%S' )
 
d2 = datetime.datetime.strptime( '2015-03-02 17:31:20' , '%Y-%m-%d %H:%M:%S' )
 
Print (d1)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 
2015 - 03 - 05 17 : 41 : 20

5、计算时间差的方法

?
1
2
3
4
5
6
7
8
9
10
11
for i in range ( 20 ):
 
    d3 = datetime.datetime.now()
 
    print (d3 - d1)
 
    time.sleep( 1 )<br> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 
2015 - 03 - 05 17 : 41 : 20
 
1100 days, 16 : 05 : 16.123119

6、与time.timedelta()结合计算时间

?
1
2
3
4
5
6
7
print (d1 + datetime.timedelta( 3 )) 三天后的时间
 
print (d1 + datetime.timedelta( - 3 )) 三天前的时间
 
Primt(datetime.now + datetime.timedelta(hour = 3 )) 三小时后的时间
 
Primt(datetime.now + datetime.timedelta(second0 = - 3 )) 三秒前的时间

7、时间的修改与替换

?
1
2
3
4
5
6
7
8
9
10
11
12
13
nownow = datetime.datetime.now()
 
print ( type (nownow))
 
nownow.replace(year = 1999 )
 
print (nownow,nownow.replace(year = 1999 ))
 
- - - - - - - - - - - - - - - - -
 
  < class 'datetime.datetime' >
 
2018 - 01 - 04 02 : 31 : 29.952321 1999 - 01 - 04 02 : 31 : 29.952321

  注意:除非重新赋值给新的变量 不然replace不会去改变变量本身 和字符串类似

 

四、random 模块,随机数模块的使用

 

1、random.random()

生成随机浮点数范围在0-1之间 包括0不包括1

 

?
1
2
>>> random.random()
0.11288859525093142

 

2、random.randint() 

生成随机整数,前数字都包含,即生成的随机数前后数字都可能出现

?
1
2
3
4
5
6
>>> random.randint( 1 , 4 )
1
>>> random.randint( 1 , 4 )
3
>>> random.randint( 1 , 4 )
4

 

3、random.randrange()

顾头不顾尾的range,可以设置步长,不设置step 则step为1.

randint不能设置步长step

 

?
1
2
3
4
5
6
>>> random.randrange( 0 , 11 , 2 )
4
>>> random.randrange( 0 , 11 , 2 )
8
>>> random.randrange( 0 , 11 , 2 )
0

 

4、random.choice()

放入一个非空序列 列表 字符串 元组(有序的,放入字典、集合会报错)

 

?
1
2
3
4
5
6
7
8
9
10
11
12
>>> random.choice(( 1 , 2 , 3 , 4 )) #元组
3
>>> random.choice(( 1 , 2 , 3 , 4 ))
2
>>> random.choice([ 'a' , 'b' , 'c' ])
'c'
>>> random.choice([ 'a' , 'b' , 'c' ])
'a'
>>> random.choice( 'python' ) #字符串
'y'
>>> random.choice( 'python' )
'o'

 

5、random.sample()取多个,与choice类似,choice取1个,sample取多个

 放入一个非空序列,第二个参数表示抽取多少个,组成列表

 

?
1
2
3
4
>>> random.sample([ 'a' , 'b' , 'c' ], 2 )
[ 'b' , 'c' ]
>>> random.sample( 'python' , 6 )
[ 'o' , 't' , 'h' , 'p' , 'y' , 'n' ]

 

6、random.uniform() 指定区间的浮点数

和random.random做对比 random只是0和1之间

 

?
1
2
3
4
>>> random.uniform( 1 , 4 )
1.5855347763788947
>>> random.uniform( 1 , 4 )
3.890550444129729

 

7、洗牌功能 random.shuffle()对列表进行乱序

 

 同时要注意是他可以直接改变列表 不需要重新赋值出来

 

?
1
2
3
4
5
>>> a = [ 1 , 2 , 3 , 4 ]
>>> random.shuffle(a)
>>> a
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ 4 , 1 , 3 , 2 ]

 

8、生成验证码的程序一则

 

思路  

    random.randint(0-9)

 

    random.randint(65-90)

 

    Chr(数字)->字符

 

    字符串相加 ‘abc’+’d’=’abcd’

 

?
1
2
3
4
5
6
7
8
9
10
def yanzheng():
    yanzhengma = ''
    for i in range ( 4 ):
        shuzi_or_zimu = random.randint( 0 , 1 )
        if shuzi_or_zimu:
            yanzhengma + = str (random.randint( 0 , 9 ))
        else :
            yanzhengma + = chr (random.randint( 65 , 90 ))
    print (yanzhengma)<br> for i in range ( 5 ):
       yanzheng()<br> - - - - - - - - - - - - - - - - - - - - - - - - - - - -

1F47 YR31 R80M 66FG F6GS 

五、os模块

os模块分两个部分来讲:1、 常用函数 2、os.path

(一)os的常用函数

1、os.getcwd() 相当于pwd

获取当前python程序运行的路径 你这个.py文件在哪 他就显示哪

2、os.chdir()

相当于linux的cd 到相应目录项进行操作

注意的是chdir的时候

对于目录\的两种处理方式

2.1、\\

2.2、r

复制代码
>>> os.getcwd()
'C:\\Users\\Raytine'
>>> os.chdir('d:\') File "<stdin>", line 1 os.chdir('d:\') ^ SyntaxError: EOL while scanning string literal >>> os.chdir('d:\\') >>> os.getcwd() 'd:\\' >>> os.chdir(r'c:\') File "<stdin>", line 1 os.chdir(r'c:\') ^ SyntaxError: EOL while scanning string literal >>> os.chdir(r'c:\\') >>> os.chdir(r'c:\a') >>> os.getcwd() 'c:\\a'
复制代码

注意:为什么>>> os.chdir(r'c:\')报错 ,os.chdir(r'c:\')

3、os.curdir 当前目录  os.pardir 上一级目录

>>> os.curdir #只是个变量,并不能引用
'.'
>>> os.curdir
'.' >>> os.pardir

注意点:  os.curdir 和os.pardir 都没有()引用,不是函数

4、os.makedirs(r'c:\a\b\c') 递归创建

5、os.removedirs(r'c:\a\b\c')递归删除

删除原则:目录为空继续删,不能用来删文件及删除非空目录

复制代码
>>> os.removedirs(r'c:\a\b\1.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> File "D:\Python36\lib\os.py", line 238, in removedirs rmdir(name) NotADirectoryError: [WinError 267] #目录名称无效。: 'c:\\a\\b\\1.txt' >>> os.removedirs(r'c:\a\b\c') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\Python36\lib\os.py", line 238, in removedirs rmdir(name) OSError: [WinError 145] #目录不是空的。: 'c:\\a\\b\\c' >>> os.removedirs(r'c:\a\b\c')
复制代码

6、os.mkdir() 创建目录

不会递归,如果前面不存在则创建不成功

7、os.rmdir()删除目录

不会递归,为空删除

8、os.listdir(os.curdir) 

列出文件夹下面的所有文件 以列表形式列出

>>> os.listdir('.')
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python.pdb' ]

9、os.remove('filename') 删除文件

10、os.rename('oldname','newname')

可以改文件夹名字以及文件的名字

>>> os.makedirs(r'c:a\b\c\d')
>>> os.rename(r'c:a\b\c\d',r'c:a\b\c\e')

11、os.stat() 查看文件的属性

>>> os.stat(r'c:a\b\c\e')
os.stat_result(st_mode=16895, st_ino=1125899906960658, st_dev=2766884258, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1519743765, st_mtime=1519743765, st_ctime=1519743765)

12 os.sep 路径分隔符 windows \\ linux /

13 os.linesep 换行符 windows \r\r linux \n

14 os.pathsep 分割文件路径的分隔符 ;

复制代码
>>> os.pathsep
';'
>>> os.linesep
'\r\n' >>> os.sep '\\' >>>
复制代码

注意点:都没有括号引用

15、os.environ 输出系统的环境变量 为一个字典

和sys.path 不同 sys.path为python的环境变量

environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\linyuming.ESG\\AppData\\Roaming', 'WINDIR': 'C:\\Windows'})

16.os.name 系统名称

windows 为‘nt’  获取系统name针对不同系统做不同操作,增加兼容性

Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

>>> os.name
'nt'

17.os.system() 用来执行系统指令

复制代码
>>> os.system('dir')

驱动器 D 中的卷没有标签。
卷的序列号是 D2E8-6B21
D:\Python36 的目录

2017/12/19 02:50 <DIR> . 2017/12/19 02:50 <DIR> .. 2017/12/19 02:50 <DIR> DLLs 2017/12/19 02:50 <DIR> Doc 2017/12/19 02:48 <DIR> include2017/12/19 02:50 <DIR> libs
复制代码

 

(二)os.path 模块

1、os.path.abspath()

获取文件的绝对路径

2、os.path.split() 切割文件路径

切割成目录+文件的形式

print(os.path.split(r'c:\a\b\c\d')) #不论文件是否存在 ('c:\\a\\b\\c', 'd')# 返回二元组,第一部分为目录 第二部分为文件名 #Split=dirname+basename

3、os.path.dirname(r'c:\a\b\c\d.txt')获取文件的目录

不论这个文件是否存在,实质就是切割路径

4 、os.path.basename(r'c:\a\b\c\d.txt') 获取文件名

这个和dirname相对,basename只取文件名

复制代码
>>> os.path.dirname(r'c:\a\b\c\d.txt')
'c:\\a\\b\\c' >>> os.path.basename(r'c:\a\b\c\d.txt') 'd.txt' >>> os.path.split(r'c:\a\b\c\d.txt') ('c:\\a\\b\\c', 'd.txt') #linux windows 对于路径分隔符定义不通 所以运行结果有区别 #上面的路径都可以不存在
复制代码

5、os.path.exists()判断路径是否存在

可以判断文件 或者文件夹

>>> os.path.exists(r'c:\a\b\c\d.txt')
False

6、os.path.is* 判断

复制代码
>>> os.path.isfile(r'c:\a\123')
False #文件不存在 false >>> os.path.isfile(r'c:\a\b') False #不是文件 false >>> os.path.isfile(r'c:\a\b\1.txt') True #存在且是文件 true
复制代码
复制代码
>>> os.path.isabs(r'c:\\')
True
>>> os.path.isabs(r'c:') False #写的格式不对,不是绝对路径则返回false >>> os.path.isabs(r'c:\\ajsdfiouoiw') True #不存在也返回true
复制代码

isabs(s)

Test whether a path is absolute

isdir = _isdir(path, /)

Return true if the pathname refers to an existing directory.

isfile(path)

Test whether a path is a regular file

islink(path)

Test whether a path is a symbolic link.

This will always return false for Windows prior to 6.0.

ismount(path)

Test whether a path is a mount point (a drive root, the root of a

share, or a mounted volume)

7、os.path.join 将多个名字组合成路径

拼接过程不能带分割符 不然会出现问题

>>> os.path.join('root','tmp','abc') 'root/tmp/abc' >>> os.path.join(r'/','root','tmp','abc') '/root/tmp/abc'

8、getatime/getctime获取文件的时间

复制代码
>>> time.localtime(os.path.getatime(r'c:\a\b\1.txt'))
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=27, tm_hour=23, tm_min=33, tm_sec=57, tm_wday=1, tm_yday=58, tm_isdst=0)

os.path.getatime(file) #输出最近access访问时间1318921018.0  os.path.getctime(file) #输出文件create创建时间 os.path.getmtime(file) #输出最近修改时间 #返回的是时间戳
复制代码

 

 

六、sys模块-和解释器相关的信息及操作

该部分内容较少。

sys.version 获取python解释器的版本信息

sys.stdout 标准输出

sys.argv 获取参数 第一个参数是py文件路径

sys.exit()标准退出exit(0)

print(sys.version)#输出python的信信息
print(sys.argv)#用来获取参数 第一个元素是程序路径 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] ['F:/my_python_file/20180113_sys_shutil.py']

转载于:https://www.cnblogs.com/di2wu/p/8940019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值