python函数输出写入文件

时间:2017-03-23 20:12:33

标签: python python-2.7

我想创建输出文件FileA和FileB,其中包括来自不同函数调用的输出。将'file'作为参数传递给每个适当的函数并附加到它是否更好?或者还有其他任何智能方式来处理它吗?谢谢!

Output:
FileA contains OutA1, OutA2
FileB contains OutB1, OutB2

(python2.7)

def taskA1_func:
  <code>
  for lines in <code>:
    yield OutA1

def taskA2_func:
  <code>
  for lines in <code>:
    yield OutA2

def taskB1_func:
  <code>
  for lines in <code>:
    yield OutB1

def taskB2_func:
  <code>
  for lines in <code>:
    yield OutB2

write_to_file_func:
    creates file FileA and FileB

main()

1 个答案:

答案 0 :(得分:0)

从Python 2.7(或3.1)开始,您可以使用:

with open('FileA.txt', 'a') as FileA, open('FileB.txt', 'a') as FileB:
    FileA.write('something')
    FileB.write('something else')