使用Python将文件打印到文件中

问题描述 投票:71回答:6

类的项目涉及解析Twitter JSON数据。我正在获取数据并将其设置到文件中没有太多麻烦,但它只是一行。这对于我正在尝试的数据操作很好,但是文件非常难以阅读,我无法很好地检查它,使得为数据操作部分编写代码非常困难。

有没有人知道如何从Python中做到这一点(即不使用命令行工具,我无法工作)?到目前为止,这是我的代码:

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "wb")
# magic happens here to make it pretty-printed
twitterDataFile.write(output)
twitterDataFile.close()

注意我很感激有人指着我简单的文档等等,但正如我所说,我已经看过并继续需要帮助。一个真正有用的回复将比那里的例子更详细和更具说明性。谢谢

另外:在Windows命令行中尝试此操作:

more twitterData.json | python -mjson.tool > twitterData-pretty.json

结果如下:

Invalid control character at: line 1 column 65535 (char 65535)

我会给你我正在使用的数据,但它非常大,你已经看到了我用来制作文件的代码。

python json twitter pretty-print
6个回答
66
投票
header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

56
投票

你可以解析JSON,然后用这样的缩进再次输出它:

import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)

有关更多信息,请参阅http://docs.python.org/library/json.html


41
投票
import json

with open("twitterdata.json", "w") as twitter_data_file:
    json.dump(output, twitter_data_file, indent=4, sort_keys=True)

如果您不想稍后解析字符串,则不需要json.dumps(),只需使用json.dump()即可。它也更快。


14
投票

您可以使用python的json模块进行打印。

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

所以,在你的情况下

>>> print json.dumps(json_output, indent=4)

3
投票

如果您已经有想要格式化的现有JSON文件,可以使用:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

-2
投票

您可以将文件重定向到python并使用该工具打开并阅读它使用更多。

示例代码将是,

cat filename.json | python -m json.tool | more
© www.soinside.com 2019 - 2024. All rights reserved.