如何缩短我的代码来编写一个简单的文本文件?

时间:2014-08-04 03:02:10

标签: python

我的数据作为变量:

Brazil = 55
USA = 12
Greece = 32
India = 56

现在,我想生成如下所示的文本文件:

Brazil 55
USA 12
Greece 32
India 56

with open ('result.txt','w') as fo:
  fo.write('Brazil' + ' ' + str(Brazil) + '\n')
  fo.write('USA' + ' ' + str(USA) + '\n')
  fo.write('Greece' + ' ' + str(Greece) + '\n')
  fo.write('India' + ' ' + str(India) + '\n')

我的代码有效,但我怎样才能缩短它?我使用的是Python 2.7

4 个答案:

答案 0 :(得分:5)

import collections
vals = collections.OrderedDict([("Brazil", 55), ("USA", 12), ("Greece", 32), ("India", 56)])
with open('result.txt', 'w') as fo:
    for country,score in vals.iteritems():
        fo.write("%s %d\n" %(country, score))

答案 1 :(得分:0)

替代方案,短线1线,无进口:

dict = {'Brasil':55, 'USA':12, 'Greece':32, 'India':56,}
with open("result.txt", "w") as fd:
    for c in dict:
        fd.write("%s %d\n" % (c, dict[c]))

编辑我用print而不是fd.write

进行了测试

@Burhan Khalid,我举起你的2班:

dict = {'Brasil':55, 'USA':12, 'Greece':32, 'India':56,}
open("result.txt", "w").write("\n".join(['%s %d' % (c, v) for c,v in dict.iteritems()]))

并且GvR可以原谅我们没有明确关闭文件......

另外,从这里开始,一个班轮很明显,只需在列表理解中加入词典。

答案 2 :(得分:0)

与检查员小工具相同的答案,但使用较新的样式字符串格式(我认为它更清晰,更容易使用):

import collections
vals = collections.OrderedDict([("Brazil", 55), ("USA", 12), ("Greece", 32), ("India", 56)])
with open('result.txt', 'w') as fo:
    for country,score in vals.iteritems():
        fo.write("{} {}".format(country, score))

答案 3 :(得分:0)

三行版本:

d = {'Brasil':55, 'USA':12, 'Greece':32, 'India':56}
with open('result.txt', 'w') as fo:
    fo.write('\n'.join('{} {}'.format(a, b) for a,b in d.iteritems()))