def file_name(url): for root, dirs, files in os.walk(url): for i in range(len(files)): f = open('c:/test/txt/file/' + files[i][:files[i].index('.txt')] + '.txt') next(f) for j in f: res = j.split(' ') obj = {} for k in res: if len(res) > 2: obj = { "trade_date": res[0], "time": res[1], "open": float(res[2]) if res[2] else '', "high": float(res[3]) if res[3] else '', "low": float(res[4]) if res[4] else '', "close": float(res[5]) if res[5] else '', "vol": float(10) } if obj and obj['trade_date'] != '': name = files[i][:files[i].index('.txt')] origin = client['abc'][name] origin.insert_one(obj) # print() print(i, files[i][:files[i].index('.txt')], 'end')