[英]How to add newline to end of file.write()?
I have a simple python script that outputs to an author.json
file. 我有一个简单的python脚本输出到
author.json
文件。 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
? 在
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 - 对于Python 3.x,你也可以使用
print()
函数,它会为你添加换行符,所以不用output.write()
,你会做 -
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 - 文件
a.txt
包含 -
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; 我希望你意识到你的脚本只会在输出中有最后一个id的值; 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. 因此,即使原始文件中有5个
id
值,结果数据中也只有一个值。
put.write(json.dumps("author\n", indent=4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.