【问题标题】:How to add newline to end of file.write()?如何在 file.write() 末尾添加换行符?
【发布时间】:2015-11-01 13:43:51
【问题描述】:

我有一个输出到author.json 文件的简单python 脚本。问题是它没有在文件末尾包含换行符。

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

【问题讨论】:

  • output.write('\n') ?或print(json.dumps(author, indent=4),file=output)
  • 嘿,你知道什么 =) 它有效。谢谢。

标签: python json python-3.x


【解决方案1】:
put.write(json.dumps("author\n", indent=4))

【讨论】:

  • 原问题中author是一个变量,不是字符串。
【解决方案2】:

对于 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

【讨论】:

    【解决方案3】:

    手动添加行尾:

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

    我希望你意识到你的脚本在输出中只会有最后一个 id 的值;因为您正在覆盖循环中的键(字典不能有重复的键)。

    因此,即使原始文件中有 5 个 id 值,结果数据中也只有一个值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多