2017-03-23 180 views
0

我想創建輸出文件FileA和FileB,其中包含來自不同函數調用的輸出。將「文件」作爲參數傳遞給每個相應的函數並將其附加到它會更好嗎?或者有沒有其他智能的方法來處理它?謝謝!python函數輸出寫入文件

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

回答

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

檢查你的答案 – abccd

+0

的感謝!修正了 – mmenschig

+1

還有問題... – abccd