模块

来源:互联网 发布:粒子群算法 详解 ppt 编辑:程序博客网 时间:2024/05/17 09:16

模块与包的管理

模块

  • 模块实质上就是一个以.py结尾的文件,可以被其他py文件调用;
  • 导入模块时,会去python的默认搜索路径中寻找;
  • python的默认搜索路径sys.path
  • 添加自定义的搜索路径时,sys.path是一个列表,
    sys.apth.append(“path”);
    - sys.path.append(“/home/kiosk/1-Pythonv3/day08/code”)
    - sys.path.insert(0,’/home/kiosk’)
  • 导入一个模块的实质是将模块的文件重新运行一次;
  • 导入模块的方法:
    import module1,module2
    from 模块名 import 函数名
    from 模块名 import 函数名 as 函数别名
    import 模块名 as 函数别名

  • 导入一个包的实质是运行包里面的init.py文件;
  • 导入包的方法:
    import 包名
    from 包名 import 模块名
    import 包名(注意init.py函数的内容)
    常用的两种方法:
    1>在调用模块:
    from 包 import 模块
    访问:模块.函数()
    2>被调模块:
    init.py中:import 模块
    调用模块:
    import 包
    访问:包.模块.函数()
    • 其他包中的模块

      import sys
      sys.path.append("包的绝对路径")
      import logout #导入模块
      print logout.logout()

模块分类:

- 内置模块(os,sys,time)- 自定义模块- 第三方模块 #开源

微信男女统计:

import itchatitchat.login()# itchat.send("hello","filehelper")itchat.auto_login(hotReload=True)friends=itchat.get_friends(update=True) #列表print friendsmale=female=other=0for i in friends[1:]:    sex=i["Sex"]    if sex==1:        male+=1    elif sex==2:        female+=1    else:        other+=1print "男:%d"%maleprint "女:%d"%femaleprint "其他:%d"%otherprint len(friends)

常用的内置模块

os,sys,time,datetime,json/pickle,shutil,random
例:统计/var/log下以.log结尾的文件。

import osfilename=raw_input("please input filename:")f=open(filename,"w+")for file in os.listdir("/var/log/"):    if file.endswith(".log"):        f.write(file+"\n")f.seek(0,0)print f.read()f.close()

这里写图片描述

原创粉丝点击