簡體   English   中英

JSON 格式 - 多行的多個文件

[英]JSON Formatting - Multiple Files with Multiple Rows

我有多個文件,我需要將它們格式化為一個 JSON 文件:

這是我擁有的文件示例:

{“t”:“測試”,“標題”:“測試”,“內容”:“測試”}

{"t": "test2", "title": "test2", "content": "test2"}

我需要的是:

[

{"t": "test", "title": "test", "content": "test"},

{"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")

我知道我在這里遺漏了一些代碼,這些代碼輸入到我目錄中的每個文件中......或者可能是其他東西? 有人可以幫我弄這個嗎?

如果您只需要在目錄中的每個文件周圍添加{} ,這很容易做到:

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 的文本文件
  • 從字面上看,只添加{}會產生正確的輸出文件
  • 給定目錄中的文件沒有被另一個進程同時修改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM