我有一个5行长的JSON文件。我想将每一行写到一个单独的文件中,即将line1
写入file1
,将line2
写入file2
等
现在,我试图将文件写入文件中,但是数据排成一行并且混乱,并且在写入文件中的每个键和值之前都有一个奇怪的'u'。
import json
with open("test1.json") as f:
with open("1.json","w") as o:
lines = f.readline()
for line in lines:
y = json.loads(line)
print(y)
json.dump(y,o)
答案 0 :(得分:1)
linecount = 0
with open("test1.json") as f:
lines = f.readline()
for line in lines:
linecount = linecount + 1
with open(str(linecount)+".json","w") as o:
y = json.loads(line)
print(y)
o.writelines(y)
已更新:添加了@tripleee建议
fp = open("test1.json",'r')
for i, line in enumerate(fp):
with open(str(i)+".json","w") as o:
y = json.loads(line)
print(y)
o.writelines(y)
除此行with open("1.json","w") as o:
外,您的代码看起来都很不错
更改此行以为每行创建新文件
逻辑是-计算行数,使用linecount.json创建文件并转储json
答案 1 :(得分:1)
最有效的方法是:
with open('test1.json').readlines() as json_data: # readlines returns a list containing each line as seperate items
for i in range(len(json_data)): # For loop allows this to work with any number of lines
file = open(f'{str(i+1)}.json', 'w') # Same as '{str(i+1)}.json'.format() or str(i+1)+'.json'
file.write(json_data[i])
file.close()
# print(json.loads(json_data[i]) # Uncomment if you want to print the content of each line
这使您可以处理任意数量的行-为您动态命名输出文件。
字符串前面的u
(如u'string'
)表示unicode字符串。现在已弃用python语言-默认字符串类型是unicode。现在仅在python 3中才与python 2兼容。