单文件夹进行遍历:
import os def gen_tree(filepath, parent): status = [filepath, 'd', ' '] parent.append(status) files = os.listdir(filepath) for fi in files: fi_d = os.path.join(filepath, fi) if os.path.isdir(fi_d): child = [] gen_tree(fi_d, child) if child: parent.append(child) else: status = [os.path.join(filepath, fi_d), 'f', ''] parent.append(status) if __name__=='__main__': file_tree = [] gen_tree(r'F:/test',file_tree) print(file_tree)两个文件夹
import os orig_pathA = None orig_pathB = None # flag = 0, pathA and pathB are all valid # flag = 1, pathA is valid, pathB is empty # flag = 2, pathA is empty, pathA is valid def gen_tree(path, flag, parent): status = [path, 'd', flag] parent.append(status) if flag == 0: # do 2 tree cmp else: files = os.listdir(path) for fi in files: fi_d = os.path.join(path, fi) if flag == 1: realpath = os.path.join(orig_pathA, fi_d) else: realpath = os.path.join(orig_pathA, fi_d) if os.path.isdir(realpath): child = [] gen_tree(fi_d, flag, child) if child: parent.append(child) else: status = [os.path.join(path, fi_d), 'f', flag] parent.append(status) def compare_file(pathA, pathB): return 0 if __name__=='__main__': file_tree = [] pathA = r'F:/testA' pathB = r'F:/testB' if os.path.isdir(pathA) and os.path.isdir(pathB): orig_pathA = pathA orig_pathB = pathB gen_tree('.', 0, file_tree) elif os.path.isfile(pathA) and os.path.isfile(pathB): issame = compare_file(pathA, pathB) statusA = [pathA, 'f', issame] statusB = [pathB, 'f', issame] file_tree.append(statusA) file_tree.append(statusB) else: print('path is not valid or type mismatch!') print(file_tree)