python内置模块

友情链接

武沛齐:http://www.cnblogs.com/wupeiqi/articles/4963027.html

金角大王:http://www.cnblogs.com/alex3714/articles/5161349.html

 

内置模块:

1.OS

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

os.chdir( "dirname" )  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ( '.' )
os.pardir  获取当前目录的父目录字符串名:( '..' )
os.makedirs( 'dirname1/dirname2' )    可生成多层递归目录
os.removedirs( 'dirname1' )    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir( 'dirname' )    生成单级目录;相当于shell中mkdir dirname
os.rmdir( 'dirname' )    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir( 'dirname' )    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename( "oldname" , "newname" )  重命名文件 / 目录
os.stat( 'path/filename' )  获取文件 / 目录信息
os.sep    输出操作系统特定的路径分隔符,win下为 "\\",Linux下为" / "
os.linesep    输出当前平台使用的行终止符,win下为 "\t\n" ,Linux下为 "\n"
os.pathsep    输出用于分割文件路径的字符串
os.name    输出字符串指示当前使用平台。win - > 'nt' ; Linux - > 'posix'
os.system( "bash command" )  运行shell命令,直接显示
os.environ  获取系统环境变量
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所指向的文件或者目录的最后修改时间
 
2.time & datetime模块
 
1 import time
2 # t = time.time()
3 # print(t)
4 # print(time.clock())
5 # print(time.gmtime(1500353542.180765))
6 # print(time.localtime())
7 # print(time.asctime())
8 print(time.strftime("%Y-%m-%d %H:%M:%S---%A ",time.localtime())) #打印时间
9 详细可查看time()模块系统解释
View Code

注:时间加减计算可查看金角大王博客

 

3.random模块

 

使用随机数生成随机验证码:

随机数函数
import random
print random.random() print random.randint(1,2)include 2 print random.randrange(1,10)#exclude 10
验证码
#简写版,只有大写字母和数字
import
random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp) print checkcode

 
   

 

#详细版,大小写字母和数字
for
i in range(5): current = random.randrange(0,4) if current != i: count = random.randint(65,122) if count in range(91,97): temp = 'x' else: temp = chr(count) else: temp = random.randint(0,9) checkcode += str(temp) print(checkcode)

 



 4.json 和 pickle 

 

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

什么东西能用pickle模块存储?

–所有Python支持的 原生类型 : 布尔, 整数, 浮点数, 复数, 字符串, bytes(字节串)对象, 字节数组, 以及 None.
–由任何原生类型组成的列表,元组,字典
–由任何原生类型组成的列表,元组,字典和集合组成的列表,元组,字典和集合(可以一直嵌套下去,直至Python支持的最大递归层数).
–函数,类,和类的实例(带警告)。

 

经验:1.json可以用来操作txt文件,但是遇到保存字典的时候,请使用双引号 " ,使用单引号会报错!

           2.pickle只能操作二进制的文件!文件读写一定要是wb,rb

           3.pickle序列化类,函数,对象等,取的时候要再次声明!虽然序列化类和函数并没有什么用,但是对象可以存取。

5.shelve 模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

import shelve
 
d = shelve.open('shelve_test') #打开一个文件
 
class Test(object):
    def __init__(self,n):
        self.n = n
 
 
t = Test(123) 
t2 = Test(123334)
 
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t      #持久化类
d["t2"] = t2
 
d.close()

读取
# print(d.get('t1').n)
 
  

 6.ConfigParser模块

用于生成和修改常见配置文档,以下是使用方法:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

生成上面的文档

import configparser
 
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
 
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)

增删改查

读的方式跟字典很想,如:config['DEFAULT']['compression'],还可以用get方法, 迭代方法等

[section1]
k1 = v1
k2:v2
  
[section2]
k1 = v1
 
import ConfigParser
  
config = ConfigParser.ConfigParser()
config.read('i.cfg')
  
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
  
#item_list = config.items('group2')
#print item_list
  
#val = config.get('group1','key')
#val = config.getint('group1','key')
  
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
  
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
  
  
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
  
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

 

7.logging 模块

 

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

简单的用法:

import logging
logging.basicConfig(filename='test.log',format="%(pathname)s "
                    "%(module)s %(asctime)s---%(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S",level="DEBUG")
logging.warn("warning...")
logging.debug("debuging...")
logging.info("info...")
logging.error("error...")

打印出来结果:

D:/myProject/day5/log.py log 2017-07-19 11:40:36---warning...
D:/myProject/day5/log.py log 2017-07-19 11:40:36---debuging...
D:/myProject/day5/log.py log 2017-07-19 11:40:36---info...
D:/myProject/day5/log.py log 2017-07-19 11:40:36---error...

更多详情, 如打印到屏幕,请参考金角大王博客!

 

8.re正则表达式

 

这部分没有什么好说的,多练,时常练,参考金角大王博客。

转载于:https://www.cnblogs.com/iforelse/p/7199115.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值