码迷,mamicode.com
首页 > 编程语言 > 详细

python学习-常用模块-os,random,logging

时间:2017-05-27 00:39:02      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:程序   arc   getc   文件中   logs   rect   import   绝对路径   脚本   

os模块(补充中)

1.查看当前路径及切换路径

>>> import os
>>> os.getcwd()  #获取当前文件所在的路径
‘D:\\python\\Lib\\idlelib‘
>>> os.chdir(‘../‘)  #切换当上一层目录,此处可以是相对路径
>>> os.getcwd()
‘D:\\python\\Lib‘

>>> os.chdir(‘D:\Program Files (x86)‘)  #也可以是绝对路径
>>> os.getcwd()
‘D:\\Program Files (x86)‘

补充:

在pycharm上发现os.getcwd()与os.path.realpath("./")返回的都是.py文件的绝对路径,其实不是的,这个目录并不是指脚本所在的目录,而是所运行脚本的目录。

实际上os.path.relpath(path[, start])  #从start开始计算相对路径。

print(__file__)·#返回文件的相对路径,包含文件名称

os.path.abspath(__file__)#返回文件的绝对路径,包含文件名称

os.path.dirname(os.path.abspath(__file__))#上一个路径的文件名称所在的目录,就是当前文件的上一层

dis_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#再往上一层,可以利用这条,通过import sys; sys.path.append(dis_path),将其加到环境变量中,这样就可以实现跨路径调用文件。

2.查看当前路径下的文件是否存在

os.path.exists(‘文件名‘),存在返回True

可以结合上面的切换路径使用,查看不同路径下有没有此文件

3,替换与重命名文件

os.repalce()

replace(*args, **kwargs): 

Rename a file or directory, overwriting the destination.
前面文件用后面文件名替换

os.rename()

用法一样,但是有个区别

os.replace(f1,f2) #f2如果存在,f1仍然更名为f2,并将f2替换掉

os.rename(f1,f2)#f2如果存在,就报错

random模块 

1 import random
2 print(random.random())  #打印一个随机的float数
3 print(random.randint(1,5)) #打印1到5之间随机的int数,包括1和5
4 print(random.randrange(1,5))  #打印1到5之间随机的int数,包括1,不包括5

输出:

0.3706594058307373
4
2

实例:生成验证码

 1 import random
 2 checkcode = ‘‘
 3 for i in range(4):
 4     current = random.randrange(0,4)
 5     if current != i:
 6         """chr()返回整数对应的ASCII码中的英文字母,这里65-90代表26个大写字母,97-122返回26个小写字母。相反,ord(‘a‘)返回字母a在ascii中对应的数字"""
 7         temp = chr(random.randint(65,90))
 8     else:
 9         temp = random.randint(0,9)
10     checkcode += str(temp)
11 print(checkcode)

logging模块(补充中) 

日志共有6个级别,由高到低如下:

CRITICAL = 50

FATAL = CRITICAL

ERROR = 40

WARNING = 30

WARN = WARNING

INFO = 20

DEBUG = 10

NOTSET = 0

 

1,默认情况下,longging只会讲warning以上的级别的日志打印到屏幕上,包括warning。

import logging

 

# logging.basicConfig()

 

logging.debug(‘this is debug‘)

logging.info(‘this is info‘)

logging.warning(‘this is warning‘)

logging.error(‘this is error‘)

logging.critical(‘this is critical‘)

 

输出:

WARNING:root:this is warning

ERROR:root:this is error

CRITICAL:root:this is critical

 

 

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

import logging

logging.basicConfig(filename=‘log.log‘,

                    format=‘%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s‘,

                    datefmt=‘%Y-%m-%d %H:%M:%S %p‘,

                    level=10)

 

logging.debug(‘this is debug‘)

logging.info(‘this is info‘)

logging.warning(‘this is warning‘)

logging.error(‘this is error‘)

logging.critical(‘this is critical‘)

 

会生成一个log.log的文件,并将日志追加到文件中:默认是追加。

如下:

2017-05-25 18:09:13 PM - root - DEBUG -logging mod:  this is debug

2017-05-25 18:09:13 PM - root - INFO -logging mod:  this is info

2017-05-25 18:09:13 PM - root - WARNING -logging mod:  this is warning

2017-05-25 18:09:13 PM - root - ERROR -logging mod:  this is error

2017-05-25 18:09:13 PM - root - CRITICAL -logging mod:  this is critical

?

 

logging.basicConfig函数各参数:

filename: 指定日志文件名

filemode: 和file函数意义相同,指定日志文件的打开模式,‘w‘或‘a‘

format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

 %(levelno)s: 打印日志级别的数值

 %(levelname)s: 打印日志级别名称

 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]

 %(filename)s: 打印当前执行程序名

 %(funcName)s: 打印日志的当前函数

 %(lineno)d: 打印日志的当前行号

 %(asctime)s: 打印日志的时间

 %(thread)d: 打印线程ID

 %(threadName)s: 打印线程名称

 %(process)d: 打印进程ID

 %(message)s: 打印日志信息

datefmt: 指定时间格式,同time.strftime()

level: 设置日志级别,默认为logging.WARNING

stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

以上日志模块参考:http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html

python学习-常用模块-os,random,logging

标签:程序   arc   getc   文件中   logs   rect   import   绝对路径   脚本   

原文地址:http://www.cnblogs.com/cq90/p/6886397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!