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 example, you can use the echo command to append the text to the end of the file as shown. Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.
We used the f. write('\n') to add a new line after each line because the f. write() method does not add a newline character ('\n') automatically at the end of the line. Hence, you have to explicitly add '\n' character.
Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With