python读写txt和json文件
1、往txt文件中写入内容
# write txt
import os
name =['a','b','c','d']
seq=['11111','22222','33333','44444']
output_dir = '/home/cqh/faceData'
emb_filename = os.path.join(output_dir, 'emb_txt.txt')
with open(emb_filename, "w") as f:
for i in range(0, len(name)):
f.write(name[i] + "\t" + seq[i] + "\n")
f.close()
运行结果如下:
2、从txt文件中读取内容
# read txt
emb_filename = '/home/cqh/faceData/emb_txt.txt'
fr = open(emb_filename)
for line in fr.readlines():
print(line)
运行结果如下:
3、往json文件中写入内容
# write json
import os
name_emb = {'a':'1111','b':'2222','c':'3333','d':'4444'}
output_dir = '/home/cqh/faceData'
emb_filename = os.path.join(output_dir, 'emb_josn.json')
jsObj = json.dumps(name_emb)
with open(emb_filename, "w") as f:
f.write(jsObj)
f.close()
运行结果如下:
4、从json文件中读取内容
# read json
emb_filename = '/home/cqh/faceData/emb_josn.json'
fr = open(emb_filename)
model=json.load(fr)
for i in model.keys():
print('key: %s value: %s' % (i, model[i]))
运行结果如下;