您的位置:首页 > 编程语言 > Python开发

Python之常用模块(一)

2016-03-06 15:35 274 查看

 

time & datatime 模块

random

os

sys

shutil

json & picle

 

time & datetime

时间戳(1970年1月1日之后的秒数,即:time.time()
格式化的字符串(如:2016-02-24 14:20 即: time.strftime('%Y-%m-%d')
结构化时间(元组包含了:年,日,星期等…time.struct_time 即:time.localtime())

 

time

improt time



print
(time.time())
#返回当前系统时间戳(1456298369.1798413)
print
(time.ctime())
#输出Tue Jan 26 18:23:48 2016 ,当前系统时间('Wed Feb 24 15:19:51 2016')


print
(time.ctime(time.time()
-
86640
))
#将时间戳转为字符串格式('Tue Feb 23 15:16:36 2016')


print
(time.gmtime(time.time()
-
86640
))
#将时间戳转换成struct_time格式(


time.struct_time(tm_year=2016,tm_mon=2,tm_mday=23,tm_hour=7,tm_min=17,tc=22,tm_wday=1,tm_yday=54,tm_isdst=0))

print
(time.localtime(time.time()
-
86640
))
#将时间戳转换成struct_time格式,但返回 的本地时间(


time.struct_time(tm_year=2016,tm_mon=2,tm_mday=23,tm_hour=15,tm_min=19,tm_sec=15,tm_wday=1,tm_yday=54,tm_isdst=0))

print
(time.mktime(time.localtime()))
#与time.localtime()功能相反,将struct_time格式转回成时间戳格式(1456298734.0)


time.sleep(4)#sleep(暂停)


print
(time.strftime(
"%Y-%m-%d %H:%M:%S"
,time.gmtime()))
#将struct_time格式转成指定的字符串格式('2016-02-24 07:26:31')


print
(time.strptime(
"2016-01-28"
,
"%Y-%m-%d"
))
#将字符串格式转换成struct_time格式(


time.struct_time(tm_year=2016,tm_mon=1,tm_mday=28,tm_hour=0,tm_min=0,tm_sec=0,tm_wday=3,tm_yday=28,tm_isdst=-1))

datetime

improt datetime

print
(datetime.date.today())
#输出格式 2016-01-26


print
(datetime.date.fromtimestamp(time.time()
-
864400
))
#2016-01-16 将时间戳转成日期格式


current_time
=
datetime.datetime.now()
#


print
(current_time)
#输出2016-01-26 19:04:30.335935


print
(current_time.timetuple())
#返回struct_time格式


datetime.replace([year[,month[,day[,hour[,minute[,second[,microsecond[,tzinfo]]]]]]]])


print
(current_time.replace(
2014
,
9
,
12
))
#输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换


str_to_date
=
datetime.datetime.strptime(
"21/11/06 16:30"
,
"%d/%m/%y %H:%M"
)
#将字符串转换成日期格式


new_date
=
datetime.datetime.now()
+
datetime.timedelta(days
=
10
)
#比现在加10天


new_date
=
datetime.datetime.now()
+
datetime.timedelta(days
=
-
10
)
#比现在减10天


new_date
=
datetime.datetime.now()
+
datetime.timedelta(hours
=
-
10
)
#比现在减10小时


new_date
=
datetime.datetime.now()
+
datetime.timedelta(seconds
=
120
)
#比现在+120s


print
(new_date)


 

%y两位数的年份(00-99)
%Y四位数的年份(0000-9999)
%m月份(01-12)
%d天,日(01-31)
%H24小时制的小时(00-23)
%I12小时制的小时(01-12)
%M分钟(00-59)
%S秒(00-59)
%a本地简化星期
%A本地完整星期
%b本地简化月份
%B本地完整月份
%c本地日期和时间
%j年内的天(001-366)
%p本地A,M或P,M
%U一个星期的天(00-53)
%w星期(0-6)
%W一年中的星期(00-53)
%x本地相应的日期
%X本地相应的时间
%Z当前时区
%%%本身

 

random

随机数

import random

random.random()                 #随机生成一个0到1之间的小数(如:0.3089169738622193,0.241230223660156)

random.randint(1,5)            #随机生成一个1到5的数(包括5)

random.randrange(1,5)     #随机生成一个1到5的数(不包括5)

实例:

生成一个验证码

import random
checkcode = ''
for i in range(4):
current = random.randint(0,4)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print checkcode


 

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所指向的文件或者目录的最后修改时间




 

sys


sys.argv           命令行参数
List
,第一个元素是程序本身路径,可以跟参数,在执行过程中可以读取到参数


sys.exit(n)        退出程序,正常退出时exit(
0
)


sys.version        获取Python解释程序的版本信息


sys.maxint         最大的
Int


sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值


sys.platform       返回操作系统平台名称








shutil

高级的文件,文件夹,压缩包 处理模块

shutil.copyfileobj(fsrc,fdst[,length])

将文件内容拷贝到另一个文件中,可以部分内容


def copyfileobj(fsrc,fdst,length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)



shutil.copyfile(src,dst)

拷贝文件


def copyfile(src,dst):
"""Copy data from src to dst"""
if _samefile(src,dst):
raise Error("`%s` and `%s` are the same file" % (src,dst))

for fn in [src,dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets,devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)

with open(src,'rb')as fsrc:
with open(dst,'wb')as fdst:
copyfileobj(fsrc,fdst)



 

 

shutil.copymode(src,dst)

仅拷贝权限。内容、组、用户均不变


def copymode(src,dst):
"""Copy mode bits from src to dst"""
if hasattr(os,'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst,mode)



shutil.copystat(src,dst)

拷贝状态的信息,包括:mode bits,atime,mtime,flags


def copystat(src,dst):

    """Copy all stat info (mode bits,atime,mtime,flags)from src to dst"""

    st = os.stat(src)

    mode = stat.S_IMODE(st.st_mode)

    if hasattr(os,'utime'):

        os.utime(dst,(st.st_atime,st.st_mtime))

    if hasattr(os,'chmod'):

        os.chmod(dst,mode)

    if hasattr(os,'chflags')and hasattr(st,'st_flags'):

        try:

            os.chflags(dst,st.st_flags)

        except OSError,why:

            for err in 'EOPNOTSUPP','ENOTSUP':

                if hasattr(errno,err)and why.errno == getattr(errno,err):

                    break

            else:

                raise



 

 

shutil.copy(src,dst)

拷贝文件和权限


def copy(src,dst):

    """Copy data and mode bits ("cp src dst").

    The destination may be a directory.

    """

    if os.path.isdir(dst):

        dst = os.path.join(dst,os.path.basename(src))

    copyfile(src,dst)

    copymode(src,dst)



 

 

shutil.copy2(src,dst)

拷贝文件和状态信息


def copy2(src,dst):

    """Copy data and all stat info ("cp -p src dst").

    The destination may be a directory.

    """

    if os.path.isdir(dst):

        dst = os.path.join(dst,os.path.basename(src))

    copyfile(src,dst)

    copystat(src,dst)



shutil.copytree(src,dst,symlinks=False,ignore=None)

递归的去拷贝文件

例如:copytree(source,destination,ignore=ignore_patterns('*.pyc','tmp*'))


def ignore_patterns(*patterns):

    """Function that can be used as copytree()ignore parameter.

    Patterns is a sequence of glob-style patterns

    that are used to exclude files"""

    def _ignore_patterns(path,names):

        ignored_names = []

        for pattern in patterns:

            ignored_names.extend(fnmatch.filter(names,pattern))

        return set(ignored_names)

    return _ignore_patterns

def copytree(src,dst,symlinks=False,ignore=None):

    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.

    If exception(s)occur,an Error is raised with a list of reasons.

    If the optional symlinks flag is true,symbolic links in the

    source tree result in symbolic links in the destination tree; if

    it is false,the contents of the files pointed to by symbolic

    links are copied.

    The optional ignore argument is a callable. If given,it

    is called with the `src` parameter,which is the directory

    being visited by copytree(),and `names` which is the list of

    `src` contents,as returned by os.listdir():

        callable(src,names)-> ignored_names

    Since copytree()is called recursively,the callable will be

    called once for each directory that is copied. It returns a

    list of names relative to the `src` directory that should

    not be copied.

    XXX Consider this example code rather than the ultimate tool.

    """

    names = os.listdir(src)

    if ignore is not None:

        ignored_names = ignore(src,names)

    else:

        ignored_names = set()

    os.makedirs(dst)

    errors = []

    for name in names:

        if name in ignored_names:

            continue

        srcname = os.path.join(src,name)

        dstname = os.path.join(dst,name)

        try:

            if symlinks and os.path.islink(srcname):

                linkto = os.readlink(srcname)

                os.symlink(linkto,dstname)

            elif os.path.isdir(srcname):

                copytree(srcname,dstname,symlinks,ignore)

            else:

                # Will raise a SpecialFileError for unsupported file types

                copy2(srcname,dstname)

        # catch the Error from the recursive copytree so that we can

        # continue with other files

        except Error,err:

            errors.extend(err.args[0])

        except EnvironmentError,why:

            errors.append((srcname,dstname,str(why)))

    try:

        copystat(src,dst)

    except OSError,why:

        if WindowsError is not None and isinstance(why,WindowsError):

            # Copying file access times may fail on Windows

            pass

        else:

            errors.append((src,dst,str(why)))

    if errors:

        raise Error,errors



 

 

shutil.rmtree(path[,ignore_errors[,onerror]])

递归的去删除文件


def rmtree(path,ignore_errors=False,onerror=None):

    """Recursively delete a directory tree.

    If ignore_errors is set,errors are ignored; otherwise,if onerror

    is set,it is called to handle the error with arguments (func,

    path,exc_info)where func is os.listdir,os.remove,or os.rmdir;

    path is the argument to that function that caused it to fail; and

    exc_info is a tuple returned by sys.exc_info().  If ignore_errors

    is false and onerror is None,an exception is raised.

    """

    if ignore_errors:

        def onerror(*args):

            pass

    elif onerror is None:

        def onerror(*args):

            raise

    try:

        if os.path.islink(path):

            # symlinks to directories are forbidden,see bug #1669

            raise OSError("Cannot call rmtree on a symbolic link")

    except OSError:

        onerror(os.path.islink,path,sys.exc_info())

        # can't continue even if onerror hook returns

        return

    names = []

    try:

        names = os.listdir(path)

    except os.error,err:

        onerror(os.listdir,path,sys.exc_info())

    for name in names:

        fullname = os.path.join(path,name)

        try:

            mode = os.lstat(fullname).st_mode

        except os.error:

            mode = 0

        if stat.S_ISDIR(mode):

            rmtree(fullname,ignore_errors,onerror)

        else:

            try:

                os.remove(fullname)

            except os.error,err:

                onerror(os.remove,fullname,sys.exc_info())

    try:

        os.rmdir(path)

    except os.error:

        onerror(os.rmdir,path,sys.exc_info())



 

 

shutil.move(src,dst)

递归的去移动文件


def move(src,dst):

    """Recursively move a file or directory to another location. This is

    similar to the Unix "mv" command.

    If the destination is a directory or a symlink to a directory,the source

    is moved inside the directory. The destination path must not already

    exist.

    If the destination already exists but is not a directory,it may be

    overwritten depending on os.rename()semantics.

    If the destination is on our current filesystem,then rename()is used.

    Otherwise,src is copied to the destination and then removed.

    A lot more could be done here...  A look at a mv.c shows a lot of

    the issues this implementation glosses over.

    """

    real_dst = dst

    if os.path.isdir(dst):

        if _samefile(src,dst):

            # We might be on a case insensitive filesystem,

            # perform the rename anyway.

            os.rename(src,dst)

            return

        real_dst = os.path.join(dst,_basename(src))

        if os.path.exists(real_dst):

            raise Error,"Destination path '%s' already exists" % real_dst

    try:

        os.rename(src,real_dst)

    except OSError:

        if os.path.isdir(src):

            if _destinsrc(src,dst):

                raise Error,"Cannot move a directory '%s' into itself '%s'." % (src,dst)

            copytree(src,real_dst,symlinks=True)

            rmtree(src)

        else:

            copy2(src,real_dst)

            os.unlink(src)



shutil.make_archive(base_name,format,...)

创建压缩包并返回文件路径,例如 zip ,tar

base_name:压缩包的文件名,也可以是压缩包的路径。文件名时,保存至当前目录

format:压缩包类型,zip ,tar ,bztar ,gztar

root_dir:要压缩的文件夹路径(默认当前目录)

owner:用户,默认当前用户

group:组,默认当前组

logger:用于记录日志,通常是logging.Logger对象

 

json & pickle 模块

用于序列化的两个模块

json,用于字符串和pyhton数据类型间进行转换,所有语言中都通用

pickle,用于python特有的类型和python的数据类型间进行转换

两个模块都提供了四个功能:dumps ,dump ,loads ,load

dump :直接将序列化后的字符写到文件中

dumps:是将序列化后的字符先赋给一个变量,然后再用write方法将其写到文件中

load:直接从文件中读取内容

loads:是从内存中读取文件的内容

 

imort pickle

data = {‘k1’:123,’k2’:’hello’}

p_str = pickle.dumps(data)

 

with open(‘rueslt.pk’,’w’)as fp:


pickle.dump(data,fp)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: