[英]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')
請注意,此實現做出了幾個假設:
{
和}
會產生正確的輸出文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.