python进阶(1)——模块:开箱即用

一.开箱即用

之前总结的将模块作为函数导入程序中:https://mp.csdn.net/postedit/80904368

二.查明模块包含什么:dir()

dir(copy)

    使用help获取帮助

help(copy)
help(copy.copy)
help(copy.copy.__doc__)

  阅读模块的源代码,查找路径(注意不要对文件进行修改)

print(copy.__file__)

/anaconda3/lib/python3.6/copy.py

三. 常用的模块

1 sys模块

argv,path,modules,,,

sys.argv[]:从程序外部获取参数

当[]中为0时,

import sys
args=sys.argv[0]
print(' '.join(args))

输出:

/ U s e r s / c c d e m a c b o o k a i r / D e s k t o p / l c c t r y . p y

当[]中为1时,

import sys
args=sys.argv[1]
print(' '.join(args))

当[]中为1:时

import sys
args=sys.argv[1:]
args.reverse()
print(' '.join(args))

2 os模块

os.system用于运行外部程序

就启动web浏览器而言,使用webbrowser模块更佳

import webbrowser
webbrowser.open('http://www.python.org')

3 fileinput模块(迭代一系列文本文件中的所有行)

例1:以注释的方式给代码行的末尾加上行号,要求:

import fileinput
for line in fileinput.input(inplace=True):
    #将input的参数inplace设置为True,将就地进行处理
    line = line.rstrip()
    #rstrip将字符串末尾所有的chars字符都删除并返回结果
    num = fileinput.lineno()
    #lineo返回在当前文件中的行号
    print('{:<50} # {:2d}'.format(line,num))

运行:python lcctry.py lcctry.py

结果将对程序重新进行打印并输出

注:{:<50}表示把代码行line在50个宽度的位置靠左对齐,然后添加#num,num取2个宽度的十进制数显示,

      慎用参数inplace!!确保程序正确后再让它修改文件

3 re——正则表达式(专门下一节讨论)

猜你喜欢

转载自blog.csdn.net/weixin_40725491/article/details/83041772