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 betwe
I had the same problem because I needed to yield objects into a file because I didn't want to load the whole list of objects into memory.
Here's my approach (but I think it's a bit hacky though):
json_begin = '{"objects":['
json_end = ']}'
with open('file_data.txt', 'a') as outfile:
files = os.listdir(os.curdir)
outfile.write(json_begin)
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)
if f != files[-1]:
outfile.write(',')
outfile.write(json_end)