工作上遇到son数据的处理,写到txt文件里,再load到hive表的需求。
记录两种方法:
1. 遍历,再逐行写入:
import json
#读取json文件,提取诗词内容逐行放入txt文档
with open("./poem.json", 'r', encoding='utf-8') as f:
temp = json.loads(f.read())
for item in temp:
if len(item['paragraphs'])!=0:
str = ''
for i in item['paragraphs']:
str = str + i
with open("poem.txt", 'a', encoding='utf-8') as f:
f.write(str+"n")
2. 使用pandas:
import json
import pandas as pd
data_dict = json.loads(data_josn)
data_df = pd.Dataframe(data_dict)
# df_trans = data_dt.transpose() #如果需要转置
with open("data.txt",'w') as fw:
data_df.to_csv("xxx.txt",head=False)
参考:https://blog.csdn.net/xufankang/article/details/104538458
最后
以上就是糊涂小土豆最近收集整理的关于Python写json格式的文件到txt的全部内容,更多相关Python写json格式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复