推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fourstring
V2EX  ›  Python

Python 如何格式化输出对象到文件?

  •  
  •   fourstring · Feb 8, 2016 · 5175 views
    This topic created in 3781 days ago, the information mentioned may be changed or developed.

    如题。。。
    在做一个练手小项目,配置文件是直接用 py 源代码,里面存字典。
    现在想做成既可以手动修改配置文件,也可以程序本身支持交互式修改。问题是 Python 默认的字典输出就挤在一块了。。。这样的话用户手动修改会很不方便。
    所以请问有没有能用缩进分明的样式输出字典的方法?就像在 IDE 里手动输入字典的样子。。。
    感谢!

    8 replies    2016-02-11 17:07:25 +08:00
    11
        1
    11  
       Feb 8, 2016   ❤️ 1
    fourstring
        2
    fourstring  
    OP
       Feb 8, 2016
    @11 感谢!好棒的模块
    Daniel65536
        3
    Daniel65536  
       Feb 8, 2016   ❤️ 1
    >>> import json
    >>> config = ['foo', {'bar': ['baz', None, 1.0, 2]}]
    >>> print(json.dumps(parsed, indent=4, sort_keys=True))
    [
    "foo",
    {
    "bar": [
    "baz",
    null,
    1.0,
    2
    ]
    }
    ]

    with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)
    leeyiw
        4
    leeyiw  
       Feb 8, 2016   ❤️ 2
    JSON 、 ProtoBuf 、 Marshal 、 Pickle 都是不错的序列化库。
    RqPS6rhmP3Nyn3Tm
        5
    RqPS6rhmP3Nyn3Tm  
       Feb 9, 2016
    序列化…我喜欢 json
    KentY
        6
    KentY  
       Feb 9, 2016   ❤️ 1
    zog
        7
    zog  
       Feb 11, 2016   ❤️ 1
    import pprint
    pprint.pprint({'foo':{'bar':{'zee': 'hello'}}))

    用 pprint 这个包
    fourstring
        8
    fourstring  
    OP
       Feb 11, 2016
    @zog 是……我也才想起来这个包,被你一提醒我就想起来以前有个小玩意还用了这个……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3794 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 05:05 · PVG 13:05 · LAX 22:05 · JFK 01:05
    ♥ Do have faith in what you're doing.