【问题标题】:writing keys of a dictionary to a text file将字典的键写入文本文件
【发布时间】:2012-08-22 18:08:52
【问题描述】:

如何将字典的键逐行写入文本文件,即每行一个键?如果有任何指向相同的链接,请引导我到该链接。我可以找到将文本文件内容加载到字典中,但反之亦然。

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    如果您只想打印键(即不是值),您可以简单地遍历字典:

    with open("filename", "w") as f:
        for key in dict:
            print >>f, key
    

    或在 Python 3 中,使用新的打印功能:

    with open("filename", "w") as f:
        for key in dict:
            print(key, file=f)
    

    【讨论】:

      【解决方案2】:

      至少,这样的事情会起作用:

      fp = open('filename','w');
      for k,v in myDict.items():
       fp.write('%s=%s\n', k, v);
       #for writing just the key per line
       #fp.write('%s\n',k);
      
      fp.close();
      

      您可能需要检查键中是否存在 '=' 并使用 \r 和 \n 转义值中的 '\r' '\n'

      【讨论】:

        猜你喜欢
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多