简介
1.os模块
2.shutil模块
3.格式化模块(pprint/textwrap)
注意:这里只是简单介绍这些模块的简单使用方法,如果需要深入请查看官方文档
os模块
os.getpwd()
:获取当前路径os.chdir()
:更改当前路径,注意这里指的是程序运行时更改路径哈,配合其他函数才能看到效果os.system()
:相当于在系统控制台运行某一命令os.name
:返回系统名称
def main():
print(os.getcwd())
# 返回上一级目录
print(os.chdir('..'))
# 创建一个新的文件夹
print(os.system('mkdir fu'))
print(os.name)
shutil模块
常用于操作文件或文件夹,os模块下也提供了一些对于文件的操作
shutil.copyfile(file1,file2)
:复制文件shutil.copytree(dir1,dir2)
:复制文件夹shutil.rmtree(dir)
:删除文件夹shutil.move(path1, path2)
:移动文件或文件夹os.romve(file)
:删除文件,shutil模块未提供删除文件
在谈格式化
import reprlib
# pretty printer
import pprint
# textwrap模块格式段落文本适合给定的屏幕宽度:
import textwrap
# 模版
from string import Template
def main():
print(repr('123'))
print(repr(set('supercalifragilisticexpialidocious')))
# 定制的缩写显示大或深层嵌套的容器:
print(reprlib.repr(set('supercalifragilisticexpialidocious')))
print('------------')
t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
# 第二个参数表示对每一行输出的字符进行限制
pprint.pprint(t,width=40)
print('------------')
w = '''
The wrap() method is just like fill() except that it returns
a list of strings instead of one big string with newlines to separate
the wrapped lines.
'''
# 对段落文本进行格式化
print(textwrap.fill(w,width=40))
print('------------')
# 字符模版
te = Template('${village}folk send $$10 to $cause.')
print(te.substitute(village='Nottingham', cause='the ditch fund'))
ma = dict(village='Nottingham', cause='the ditch fund')
print(te.substitute(**ma))
print(te.substitute(ma))
# 如果没有对应的key,将会抛出KeyError
# 安全转换
# t.safe_substitute()
if __name__ == '__main__':
main()