输出到文件

时间:2011-11-27 14:13:08

标签: python

代码段:

def after_equals(s):
    return s.partition(' = ')[-1]
for k,s in zip(keyword, score):
  print after_equals(k) + ',' + after_equals(s)

代码的输出打印:

NORTH,88466
GUESS,83965
DRESSES,79379
RALPH,74897
MATERIAL,68168

我需要输入到文件中。请告知如何写入文件。

2 个答案:

答案 0 :(得分:2)

with open(filename, 'w') as out:
    for k,s in zip(keyword, score):
        print >> out, after_equals(k) + ',' + after_equals(s)
        # note:  ^^^

答案 1 :(得分:1)

以写入模式打开文件并将字符串写入文件,然后将其关闭:

f = file('myfile.txt','w')
f.write(s)
f.close()

对于你的情况:

def after_equals(s):
    return s.partition(' = ')[-1]
f = file('myfile.txt','w')
for k,s in zip(keyword, score):
  f.write('%s,%s\n' % (after_equals(k), after_equals(s)))
f.close()