我正在摆弄输出一个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": ""}
更多推荐
发布评论