import os def func(filepath): res = os.listdir(filepath) list1 = [] for k in res: ret = os.path.join(filepath,k) if os.path.isfile(ret): list1.append(ret) else: func(ret) for m in list1: with open('%s'% m,'rb')as f: f1 =f.read() with open('合并的内容','a')as f2: f3 = str(f1) f2.write(f3) return list1 x = func('../../MyFirstPython') print(x)