繁体   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