Discuss / Python / 第二题

第二题

Topic source

tangdoubley

#1 Created at ... [Delete] [Delete and Lock User]
  • 在isfile和isdir犯错了

    isfile和isdir传入的都是文件的路径,默认是当前执行程序路径,所以在子目录中需要重新合成路径

  • 添加try避免因无权限导致录取读取失败
def traversal_dir(current_path, substr):
    #print('current path %s' % current_path)
    files = []
    dirs = []
    try:
        files = [x for x in os.listdir(current_path) if os.path.isfile(os.path.join(current_path, x))] #获取目录所有文件
        dirs = [x for x in os.listdir(current_path) if os.path.isdir(os.path.join(current_path, x))] #获取目录所有目录
        #print(files)
        #print(dirs)
    except Exception as e:
        pass

    for x in files:
        if x.find(substr) >= 0:
            print(os.path.join(current_path,x))

    for x in dirs:
        nextpath = os.path.join(current_path, x)
        #print('next path %s' % nextpath)
        traversal_dir(nextpath, substr)

traversal_dir('D:', '.py')

  • 1

Reply