Python 用于使用预定义数据创建多个 JSON 文件的脚本
Python script for create multiple JSON files with predefined data
我是 Python 的新手,我的 iOS 项目有简单的要求。我想创建多个 JSON 文件,每个文件中都有一些修复数据。我用谷歌搜索了一些文章,但没有找到我真正想做的事情。那么我该如何实现呢?
以下我可以做到但没有给出预期输出的事情:
我有一个包含 100 个名字列表的 txt 文件,这个文本文件我保存在也有脚本文件的文件夹中,现在我想在同一个文件夹中为列表中的每个名字创建 txt 文件做过这样的事情:
titles = open("title.txt",'r')
for lines in titles:
output = open((lines.strip())+'.json','w')
output.write(lines.strip('\n'))
output.close()
titles.close()
此脚本已成功创建提及名称的文件。
现在我想在每个文件中写入一些预定义的修复数据。这是我的示例 json 数据,我想将此数据复制到每个文件中。我该如何实现。
{
"product": "Live JSON generator",
"version": 3.1,
"releaseDate": "2014-06-25T00:00:00.000Z",
"demo": true,
"person": {
"id": 12345,
"name": "John Doe",
"phones": {
"home": "800-123-4567",
"mobile": "877-123-1234"
},
"email": [
"jd@example.com",
"jd@example.org"
],
"dateOfBirth": "1980-01-02T00:00:00.000Z",
"registered": true,
"emergencyContacts": [
{
"name": "Jane Doe",
"phone": "888-555-1212",
"relationship": "spouse"
},
{
"name": "Justin Doe",
"phone": "877-123-1212",
"relationship": "parent"
}
]
}
}
您可以使用pprint打印文件中的数据。如果你愿意,你也可以修改 json dict 并根据需要存储它。这是一个简单的例子 -
import pprint
my_json_dict = {'some': 'data'}
titles = open("title.txt",'r')
for title in titles:
output = open((title.strip())+'.json','w')
pprint.pprint(my_json_dict, stream=output, indent=2)
output.close()
titles.close()
我是 Python 的新手,我的 iOS 项目有简单的要求。我想创建多个 JSON 文件,每个文件中都有一些修复数据。我用谷歌搜索了一些文章,但没有找到我真正想做的事情。那么我该如何实现呢?
以下我可以做到但没有给出预期输出的事情:
我有一个包含 100 个名字列表的 txt 文件,这个文本文件我保存在也有脚本文件的文件夹中,现在我想在同一个文件夹中为列表中的每个名字创建 txt 文件做过这样的事情:
titles = open("title.txt",'r')
for lines in titles:
output = open((lines.strip())+'.json','w')
output.write(lines.strip('\n'))
output.close()
titles.close()
此脚本已成功创建提及名称的文件。
现在我想在每个文件中写入一些预定义的修复数据。这是我的示例 json 数据,我想将此数据复制到每个文件中。我该如何实现。
{
"product": "Live JSON generator",
"version": 3.1,
"releaseDate": "2014-06-25T00:00:00.000Z",
"demo": true,
"person": {
"id": 12345,
"name": "John Doe",
"phones": {
"home": "800-123-4567",
"mobile": "877-123-1234"
},
"email": [
"jd@example.com",
"jd@example.org"
],
"dateOfBirth": "1980-01-02T00:00:00.000Z",
"registered": true,
"emergencyContacts": [
{
"name": "Jane Doe",
"phone": "888-555-1212",
"relationship": "spouse"
},
{
"name": "Justin Doe",
"phone": "877-123-1212",
"relationship": "parent"
}
]
}
}
您可以使用pprint打印文件中的数据。如果你愿意,你也可以修改 json dict 并根据需要存储它。这是一个简单的例子 -
import pprint
my_json_dict = {'some': 'data'}
titles = open("title.txt",'r')
for title in titles:
output = open((title.strip())+'.json','w')
pprint.pprint(my_json_dict, stream=output, indent=2)
output.close()
titles.close()