python使用os模块判断文件

基础知识

#导入os模块
import os
#判断路径是否存在(True, False)
os.path.exists('/tmp/test')
#判断目标是否是文件(True, False)
os.path.isfile('/tmp/test/file1')
#创建目录(可以递归创建)
os.makedirs('d:/assist/set')

遍历目录取出其中文件的方法

import os
def test(dir):
    for file in os.listdir(dir):
        file_basename = os.path.join(dir, file)
        #判断是否是文件,是文件就打印出来,反之,可以用来过滤目录
        if os.path.isfile(file_basename):
            print file_basename
        if os.path.isdir(file_basename):
            test(file_basename)