python标准库

来源:互联网 发布:贝爷生存刀淘宝网 编辑:程序博客网 时间:2024/06/04 19:12
os 模块:操作系统函数
>>> import os
>>> os.getcwd()
'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35'
List  a directory目录列表(列出当前目录)
>>> os.listdir(os.curdir)
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'man', 'NEWS.txt', 'python.exe', 'python3.dll', 'python35.dll', 'pythonw.exe', 'README.txt', 'Scripts', 'selenium', 'tcl', 'Tools', 'vcruntime140.dll']
Make a direcrtory创建目录
>>> os.mkdir('shuaidir')
>>> 'shuaidir' in os.listdir(os.curdir)
True
Rename the dircetory目录重命名
>>> os.rename('shuaidir','foodir')
>>> 'shuaidir' in os.listdir(os.curdir)
False
>>> 'foodir' in os.listdir(os.curdir)
True
>>> os.rmdir('foodir')
>>> 'foodir' in os.listdir(os.curdir)
False
Delete a file删除一个文件
>>> fp=open('foo.txt','w')
>>> fp.close()
>>> 'foo.txt' in os.listdir(os.curdir)
True
>>> os.remove('foo.txt')
>>> 'foo.txt' in os.listdir(os.curdir)
False
os.path系统路径操作
os.path函数为路径名提供常用操作函数
>>> fp=open('foo.txt','w')
>>> fp.close()
>>> a=os.path.abspath('foo.txt')
>>> a
'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35\\foo.txt'
split函数
>>> os.path.split(a)
('C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35', 'foo.txt')
>>> os.path.dirname(a)
'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35'
>>> os.path.basename(a)
'foo.txt'
>>> os.path.splitext(os.path.basename(a))
('foo', '.txt')
>>> os.path.exists('foo.txt')
True
>>> os.path.isfile('foo.txt')
True
>>> os.path.isdir('foo.txt')
False
运行一个外部命令os.path.walk 输出一列目录中的文件名
>>> for dirpath, dirnames, filenames in os.walk(os.curdir):
    for fp in filenames:
        print(os.path.abspath(fp))
        
C:\Users\syp\AppData\Local\Programs\Python\Python35\LICENSE.txt
C:\Users\syp\AppData\Local\Programs\Python\Python35\NEWS.txt
C:\Users\syp\AppData\Local\Programs\Python\Python35\python.exe
....
环境变量
os.environ.keys()
KeysView(environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'SYSTEMDRIVE': 'C:', 'POWERMGRPATH': 'C:\\Program Files (x86)\\Lenovo\\PowerMgr', 'SESSIONNAME': 'Console', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'NUMBER_OF_PROCESSORS': '4', 'HOMEDRIVE': 'C:', 'MSMPI_INC': 'C:\\Program Files\\Microsoft HPC Pack 2008 R2\\Inc\\', 'LOCALAPPDATA': 'C:\\Users\\syp\\AppData\\Local', 'PSMODULEPAT
......
glob module为文件名匹配提供便利
找到所有以.txt结尾的文件
>>> import glob
>>> glob.glob('*.txt')
['LICENSE.txt', 'NEWS.txt', 'README.txt']
sys模块,系统信息模块
>>> import sys
>>> sys.platform
'win32'
>>> sys.version
'3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]'
>>> sys.prefix
'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35'
>>> sys.path
['', 'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35\\Lib\\idlelib', 'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip', 'C:\\Users\\syp\\AppData\\Local\\Programs\\Python\\Python35\\DLLs',
...
原创粉丝点击