Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 571
Raphael Rafatpanah Avatar asked Aug 09 '15 15:08

Raphael Rafatpanah


People also ask

How do I add a line to the end of a file?

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.

Does F write add new line?

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.

How do I add a new line to the end of a string?

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.


2 Answers

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
like image 179
Anand S Kumar Avatar answered Sep 25 '22 15:09

Anand S Kumar


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.

like image 44
Burhan Khalid Avatar answered Sep 26 '22 15:09

Burhan Khalid