JSON格式-具有多个行的多个文件

时间:2018-10-30 18:15:59

标签: python json

我有多个文件,需要将它们格式化为一个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")

我知道我在这里缺少一些输入到目录中每个文件的代码..还是其他东西? 有人可以帮我吗?

1 个答案:

答案 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')

请注意,此实现有几个假设:

  • 硬编码的路径是有效的目录名称
  • 当前进程可读写给定目录中的每个文件
  • 给定目录中每个文件的内容都将存储在内存中
  • 给定目录中的每个文件都是一个文本文件,编码为UTF-8
  • 从字面上仅添加{}会得到正确的输出文件
  • 给定目录中的文件未被其他进程同时修改
相关问题