简体   繁体   中英

How to add newline to end of file.write()?

I have a simple python script that outputs to an author.json file. The problem is that it does not include a newline at the end of the file.

What is the best way to add a newline to the end of author.json ?

#!/usr/bin/env python

import json

with open('input.json', 'r') as handle:
    data = json.load(handle)

output = open('author.json', 'w')

author = {}

for key, value in data.items():
    if key == 'id':
        author['id'] = value


output.write(json.dumps(author, indent=4))

For Python 3.x , you can also use print() function, it will add the newline for you , so instead of output.write() , you will do -

print(json.dumps(author, indent=4),file=output)

Example/Demo -

>>> with open('a.txt','w') as f:
...     print('asd',file=f)
...     print('asd1',file=f)
...     print('asd2',file=f)

File a.txt contains -

asd
asd1
asd2

Add the end of line manually:

output.write('{}\n'.format(json.dumps(author, indent=4)))

I hope you realize that your script will only ever have the last id's value in the output; as you are overwriting the key in your loop (dictionaries cannot have duplicate keys).

So even if you have 5 id values in the original file, you'll only have one value in the resulting data.

put.write(json.dumps("author\n", indent=4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM