用json.dump逗号分隔JSON对象(Comma separator between JSON objects with json.dump)

编程入门 行业动态 更新时间:2024-10-23 12:31:48
用json.dump逗号分隔JSON对象(Comma separator between JSON objects with json.dump)

我正在摆弄输出一个json文件,其中包含目录中文件的某些属性。 我的问题是,当附加到文件时,每个对象之间没有分隔符。 我可以在每个'f'之后加一个逗号并删除最后一个,但这看起来像是一个马虎的工作。

import os import os.path import json #Create and open file_data.txt and append with open('file_data.txt', 'a') as outfile: files = os.listdir(os.curdir) for f in files: extension = os.path.splitext(f)[1][1:] base = os.path.splitext(f)[0] name = f data = { "file_name" : name, "extension" : extension, "base_name" : base } json.dump(data, outfile)

这输出:

{"file_name": "contributors.txt", "base_name": "contributors", "extension": "txt"}{"file_name": "read_files.py", "base_name": "read_files", "extension": "py"}{"file_name": "file_data.txt", "base_name": "file_data", "extension": "txt"}{"file_name": ".git", "base_name": ".git", "extension": ""}

我想要的是实际的JSON:

{"file_name": "contributors.txt", "base_name": "contributors", "extension": "txt"},{"file_name": "read_files.py", "base_name": "read_files", "extension": "py"},{"file_name": "file_data.txt", "base_name": "file_data", "extension": "txt"}{"file_name": ".git", "base_name": ".git", "extension": ""}

I am fiddling around with outputting a json file with some attributes of the files within a directory. My problem is, when appending to the file there is no separator between each object. I could just add a comma after each 'f' and delete the last one, but that seems like a sloppy work around to me.

import os import os.path import json #Create and open file_data.txt and append with open('file_data.txt', 'a') as outfile: files = os.listdir(os.curdir) for f in files: extension = os.path.splitext(f)[1][1:] base = os.path.splitext(f)[0] name = f data = { "file_name" : name, "extension" : extension, "base_name" : base } json.dump(data, outfile)

This outputs:

{"file_name": "contributors.txt", "base_name": "contributors", "extension": "txt"}{"file_name": "read_files.py", "base_name": "read_files", "extension": "py"}{"file_name": "file_data.txt", "base_name": "file_data", "extension": "txt"}{"file_name": ".git", "base_name": ".git", "extension": ""}

What I would like is actual JSON:

{"file_name": "contributors.txt", "base_name": "contributors", "extension": "txt"},{"file_name": "read_files.py", "base_name": "read_files", "extension": "py"},{"file_name": "file_data.txt", "base_name": "file_data", "extension": "txt"}{"file_name": ".git", "base_name": ".git", "extension": ""}

更多推荐

本文发布于:2023-04-29 12:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   对象   json   dump   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!