[英]Python append each string from array to a txt file
I have a json file containing this我有一个包含这个的 json 文件
[
{
"results": [
{
"names": [
"Ben",
"Sam"
]
},
{
"names": [
"John",
"Max"
]
}
]
}
]
And I want to take each string from the names array for each result and append it to a txt file called names.txt, and have each string seperated by a comma.我想从每个结果的名称数组中取出每个字符串,并将其附加到名为 names.txt 的 txt 文件中,并用逗号分隔每个字符串。 Like this
像这样
Ben, Sam, John, Max
I haven't used Python much so I'm a bit stuck with writing to another file but also on reading from the json file.我没有经常使用 Python,所以我在写入另一个文件以及从 json 文件中读取时有点卡住了。 I currently have
我目前有
with open('results.json') as json_file:
data = json.load(json_file)
for item in data['results']:
names = item['names']
And from there is where I'm just about stuck.从那里我几乎被卡住了。 Appreciate any help or advice anyone can give, thanks!
感谢任何人可以提供的任何帮助或建议,谢谢!
There's a slight problem with your JSON, the comma after "Max"
makes it invalid.你的 JSON 有一个小问题,
"Max"
后面的逗号使它无效。
If you fix that you can use this code to read the file, get a list of the names and write them to another file, results_names.txt
如果您修复了您可以使用此代码读取文件的问题,请获取名称列表并将它们写入另一个文件
results_names.txt
import json
with open('results.json') as json_file:
data = json.load(json_file)
names = []
for item in data[0]['results']:
names.extend(item['names'])
with open('results_names.txt', 'w') as txt_file:
txt_file.write(', '.join(names))
You can use an alternative method which combines opening and closing related files您可以使用结合打开和关闭相关文件的替代方法
import json
with open('results.json','r') as f_in, open('output.txt', 'w') as f_out:
data = json.load(f_in)
for i in list(range(0,len(data)+1)):
s=data[0]['results'][i]['names']
if i>0:
f_out.write(',')
f_out.write(','.join(s))
where we should be careful when putting comma between every seperate objects在每个单独的对象之间放置逗号时我们应该小心
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.