V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2016-02-08 21:39:05 +08:00 · 4525 次点击
    这是一个创建于 2992 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    8 条回复    2016-02-11 17:07:25 +08:00
    11
        1
    11  
       2016-02-08 21:43:45 +08:00   ❤️ 1
    fourstring
        2
    fourstring  
    OP
       2016-02-08 21:46:26 +08:00
    @11 感谢!好棒的模块
    Daniel65536
        3
    Daniel65536  
       2016-02-08 23:05:11 +08:00   ❤️ 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  
       2016-02-08 23:41:52 +08:00   ❤️ 2
    JSON 、 ProtoBuf 、 Marshal 、 Pickle 都是不错的序列化库。
    RqPS6rhmP3Nyn3Tm
        5
    RqPS6rhmP3Nyn3Tm  
       2016-02-09 14:11:10 +08:00
    序列化…我喜欢 json
    KentY
        6
    KentY  
       2016-02-09 18:58:31 +08:00   ❤️ 1
    zog
        7
    zog  
       2016-02-11 09:29:29 +08:00   ❤️ 1
    import pprint
    pprint.pprint({'foo':{'bar':{'zee': 'hello'}}))

    用 pprint 这个包
    fourstring
        8
    fourstring  
    OP
       2016-02-11 17:07:25 +08:00
    @zog 是……我也才想起来这个包,被你一提醒我就想起来以前有个小玩意还用了这个……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3334 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:44 · PVG 18:44 · LAX 03:44 · JFK 06:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.