我有多个文件,需要将它们格式化为一个JSON文件:
以下是我拥有的文件的示例:
{“ t”:“测试”,“标题”:“测试”,“内容”:“测试”}
{“ t”:“ test2”,“ title”:“ test2”,“ content”:“ test2”}
我需要的是:
[
{“ t”:“测试”,“标题”:“测试”,“内容”:“测试”},
{“ t”:“ test2”,“ title”:“ test2”,“ content”:“ test2”}
]
我尝试过的事情:
我有以下python代码:
import io
import os
import json
def wrap_files_in_dir(dirname):
data = {}
list_of_reviews = []
for filename in os.listdir(dirname):
file_path = os.path.join(dirname, filename)
if os.path.isfile(file_path):
with io.open(file_path, 'r', encoding='utf-8', errors='ignore') as rfile:
contents = rfile.read()
list_of_reviews.append(contents)
with io.open('AppStoreReviews.json', 'w', encoding='utf-8' , errors='ignore') as wfile:
data["reviews"] = list_of_reviews
wfile.write(unicode(json.dumps(data, ensure_ascii=False)))
if __name__ == '__main__':
wrap_files_in_dir('/Users/Jack/PycharmProjects/MyProject')
print("Your Reviews marged and converted to JSON")
我知道我在这里缺少一些输入到目录中每个文件的代码..还是其他东西? 有人可以帮我吗?
答案 0 :(得分:0)
如果您只需要在目录中的每个文件周围添加{
和}
,就很容易做到:
import io
import os
def wrap_files_in_dir(dirname):
"""For every file in the given directory, wrap its contents in brackets."""
for filename in os.listdir(dirname):
file_path = os.path.join(dirname, filename)
if os.path.isfile(file_path):
with io.open(file_path, 'r', encoding='utf-8') as rfile:
contents = rfile.read()
with io.open(file_path, 'w', encoding='utf-8') as wfile:
wfile.write(u'{\n')
wfile.write(contents)
wfile.write(u'}\n')
if __name__ == '__main__':
wrap_files_in_dir('/Path')
请注意,此实现有几个假设:
{
和}
会得到正确的输出文件