簡體   English   中英

如何在file.write()結尾添加換行符?

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

我有一個簡單的python腳本輸出到author.json文件。 問題是它不包含文件末尾的換行符。

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))

對於Python 3.x,你也可以使用print()函數,它會為你添加換行符,所以不用output.write() ,你會做 -

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

示例/演示 -

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

文件a.txt包含 -

asd
asd1
asd2

手動添加行尾:

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

我希望你意識到你的腳本只會在輸出中有最后一個id的值; 當你覆蓋循環中的鍵時(字典不能有重復的鍵)。

因此,即使原始文件中有5個id值,結果數據中也只有一個值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM