python-常用模块

#time和datetime模块

import time,datetime

print(time.localtime())  #返回本地时间的struct time 对象格式

print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

print(time.clock())   #返回处理器时间

print(datetime.datetime.now())         #获取当前时间戳

print(datetime.datetime.fromtimestamp(time.time))  #将时间戳直接转换为日期格式

print(datetime.datetime.now()+datetime.timedelta(days=5)) #当前时间戳+5天

c_time=datetime.datetime.now()

print(c_time.replace(minute=3,hour=2))#时间替换

#random随机模块

#实例-获取随机验证码

#需求:随机获取4位验证码,并且带有字母和数字

import random       

check_code=''    #定义一个字符串变量

for i in range(4):    #利用For循环进行获取,循环4次获取四次验证码

     current =random.range(0,4)      #4位验证码

     if current==i:      #判断如果第一次循环成立,则转化为字母否则转化为数字

           tempt=chr(random.randint(65,90))   #通过chr()方法将数字转化为字母

     else:

         temp=random.randint(0,9)

     check_code +=str(temp)       #转化字符串

print(check_code)   #打印输出

 

#os,sys模块

import os 

os.getcwd()    #获取当前工作目录,即当前python脚本工作的目录路径

os.chdir("dirname")    #改变当前脚本工作目录

os.curdir(".")   #返回当前工作目录

os.pardir()    #获取当前目录的父目录字符串名

os.makedirs("dirname1\dirname2")     #可生成多层递归目录

os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素

os.path.abspath(path) 返回path规范化的绝对路径

 

sys.argv    #命令行参数list,第一个元素是程序本身路径

sys.path   #设置环境变量

sys.version   #获取python的版本信息

sys.maxint    #最大的Int值

 

#ConfigParser模块

待生成的文档信息"

[DEFAULT]

ServerAliveInterval = 45

CompressionLevel=yes

CompressionLevel=9

ForwardX11=yes

[bitbucked.org]

     User=hg

[topsercret.server.com]

Port='5002'

ForwardX11='no'

 

#调用configparser模块生成上面文件

import configparser

config=configparser.configpparser()

config["DEFAULT"]={"ServerAliveInterval":"45",

                                "Compression ":"yes",

                                "Compression":"9"

}

config["bitbucked.org"]={}

config["bitbucked.org"]["User"]={'hg'}

config[“topsecret.server.com”]={}

topsecret=config[“topsecret.server.com”]

topsecret["Host Port"]="5002"

topsecret["ForwardX11"]="no"

config["DEFAULT"]["ForwardX11"]="yes"'

with open("ast.ini","w") as configfile:

        config.write(configfile)

 

#解析ast.ini文件

import configparser

conf=configparser.ConfigParser()

conf.read("ast.ini")    #调用read()方法进行读取文件

print(conf["DEFAULT"])

print(conf.defaults())

#删除操作

import configparser

conf=configparser.ConfigParser()

conf.read("ast.ini")    #调用read()方法进行读取文件

print(conf["DEFAULT"])

print(conf.defaults())

sec = conf.remove_section('DEFAULT')

conf.write(open("ast.ini","w"))

posted on 2018-08-08 15:03  凛冬08  阅读(74)  评论(0编辑  收藏  举报

导航