将哈希打印到fi

2024-06-27 20:55:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的函数,可以将用户的文件{a':1,'b':2}打印到一个新文件,如abc.txt文件,但我不知道如何正确添加infile和outfile。有人能帮我吗?如果我想替换for循环使它更简单,我该怎么做呢?你知道吗

 def pretty_printing(dict):

        order_keys = dict.keys()
        order_keys.sort()

        for key in order_keys:
            print key, dict[key]

Tags: 文件key函数用户txtfordefpretty
1条回答
网友
1楼 · 发布于 2024-06-27 20:55:29

要将输出写入'example.txt',请从以下内容开始:

with open('example.txt', 'w') as out_file:
  out_file.write(' ... whatever you want to write to the file ...\n')

要将已排序的key, dict[key]字符串连接到行中,请执行以下操作:

'\n'.join(['%s, %s' % item for item in sorted(dict.items())])

如果这对你来说太复杂了,就这样做:

for (key, value) in sorted(dict.items()):
  out_file.write('%s %s\n' % (key, value))

综合起来:

def pretty_print(dict):
  with open('example.txt', 'w') as out_file:
    for (key, value) in sorted(dict.items()):
      out_file.write('%s %s\n' % (key, value))

h = { 'a': 1, 'b': 2 }
pretty_print(h)

相关问题 更多 >