为什么会出现错误“ AttributeError:模块'pprint'没有属性'PrettyPrinter'

时间:2018-10-29 14:37:25

标签: python pprint

我正在尝试使用pprint打印出yaml文件中的值,尽管安装了pprint和导入以及所有内容,但我仍然遇到此错误

    #!/bin/python

    import yaml
    import subprocess
    import os
    import pprint

    pp = pprint.PrettyPrinter(indent=4)



    #pre-requisite-run the script in an empty directory

    #read data from the config yaml file
    def read_yaml(file):
        with open(file, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                # print(config)
            except yaml.YAMLError as exc:
                print(exc)
                print("\n")
        return config

    d = read_yaml("config.yaml")

    #print out contents of the yaml file with a better structure
    pp.pprint(d)

在命令行中运行时的错误消息:

    Traceback (most recent call last):
      File "pprint.py", line 6, in <module>
        import pprint
      File "../pprint.py", line 8, in <module>
        pp = pprint.PrettyPrinter(indent=4)
    AttributeError: module 'pprint' has no attribute 'PrettyPrinter'

1 个答案:

答案 0 :(得分:5)

您的文件名为pprint.py,因此使您要使用的pprint模块不可见。重命名您的文件。