1

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

4

2 回答 2

4

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

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

或者在 Python 3 中,使用新的 print 函数:

with open("filename", "w") as f:
    for key in dict:
        print(key, file=f)
于 2012-08-22T18:14:59.497 回答
0

At the bare minimum, something like this will work:

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();

you might need sanity checks for presence of '=' in key and escaping '\r' '\n' in value with \r and \n

于 2012-08-22T18:11:38.730 回答