将哈希打印到文件

时间:2015-09-07 04:17:51

标签: python file

我有这样的功能将用户的文件{' a':' 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]

1 个答案:

答案 0 :(得分:0)

要将输出写入df1 <- structure(list(Heading = c("Head1", "Head2", "Head3"), Years = c(2015L, 2015L, 2014L), Text = c("I am a boy and I like a girl from my class. She is pretty. I am cute.", "She is cute. She is beautiful.", "Hi, I am Jane. I play guitar. May is my friend.")), .Names = c("Heading", "Years", "Text"), class = "data.frame", row.names = c(NA, -3L)) df1N <- structure(list(Heading = c("Head1", "Head2", "Head3"), Years = c(2015L, 2015L, 2014L), Text = c("<rrrt> I am a boy and I <rrr2> like a girl <t44> from my class. She is pretty. /rr /r /r I am cute.", "She is cute. She is beautiful.", "Hi, I am Jane. I play guitar. May is my friend.")), .Names = c("Heading", "Years", "Text"), class = "data.frame", row.names = c(NA, -3L)) ,请从以下开始:

'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))