本节内容:
python os模块读取目录内容。
分享三个python 编程实例,帮助大家理解与掌握os模块的用法。
例1,列出目录信息
#!/usr/bin/python
#site: www.jb200.com
#
import os
os.listdir("c:")
dirname = "c:"
os.listdir(dirname)
print [f for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f))] [3]
print [f for f in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, f))] [4]
例2,使用glob更出目录信息
#!/usr/bin/python
#site: www.jb200.com
#
import os
os.listdir("c:")
import glob
glob.glob('c:*.mp3')
glob.glob('c:*.mp3')
glob.glob('c:c**.mp3')
例3,切换目录
#!/usr/bin/python
# site: www.jb200.com
#
import os
os.chdir('/server/accesslogs')
#Be sure to use the "import os" style instead of "from os import *". This will keep
#os.open() from shadowing the builtin open() function which operates much
#differently.