2017-02-07 78 views
-1

我有一個函數,我正在寫下如下的文件。使條件成立並將其作爲參數傳遞

def func(arg1,arg2,arg3): 
    lin=open(file1,"r") 
    lin1=open(file,"w") 
    a=lin.readline().strip('\n') 
    lin1.write(a + " " + id) 
    lin.close() 
    lin1.close() 

該函數調用到下面的另一個功能:

def afunc(arg1,arg2): 
    doing stuff 
    arg1.func(arg2,arg3) 

我想另一個參數應該在寫林1時加入:

lin1.write(a + " " + id + " " + y/n) 

但Y/N應來自用戶輸入。和該用戶輸入應該提及到第二功能afucn()

實施例:

res = str(raw_input('Do you want to execute this ? (y/n)')) 

如果我按使y應添加它LIN1並且如果並按n是n應該添加到LIN1作爲參數收率

+0

實現只要把'if'條件寫入之前? – MYGz

+0

@MYGz我試過了。但我希望用戶在「做東西」的第二個函數中做出響應。請讓我建議,如果可能的話。 – Srinivas

+1

你可以創建[mcve]嗎?在1個塊中包含完整的代碼。包括你正在談論的兩個案例的輸入和輸出? – MYGz

回答

0

我會嘗試通過查看您的代碼向您展示一些有用的提示。我看到你是新手,所以問問,如果smth會一直沒有答案。

def func(arg1,arg2,arg3): # Make sure that you use the same names here 
    # as in your actual code to avoid confusions - simplification is not a point here, 
    # especially if you are a novice 
    # also, always try to choose helpful function and variable names 
    lin=open(file1,"r") # use with context manager instead (it will automatically close your file) 
    lin1=open(file,"w") 
    a=lin.readline().strip('\n') # it reads only one line of you file, 
    # so use for loop (like - for line in f.readlines():) 
    lin1.write(a + " " + id) # it rewrites entire file, 
    # better to collect data in some python list first 
    lin.close() 
    lin1.close() 

def afunc(arg1,arg2): 
     # doing stuff # use valid python comment syntax even in examples 
     arg1.func(arg2,arg3) # func is not a method of some python Object, 
     # so it should be called as just func(arg1, arg2, arg3) 
     # when your example won't work at all 

而你的任務可能會像

def fill_with_ids(id_list, input_file, output_file): 
    with open(input_file) as inp: 
     input_lines = inp.readlines() 
    output_lines = [] 
    for i, line in enumerate(input_lines): 
     output_lines.append(line + ' ' + id_list[i]) 
    with open(output_file, 'w') as outp: 
     outp.writelines(output_lines) 


def launch(input_file, output_file): 
    confirm = input('Do you want to execute this? (y/n)') 
    if confirm != 'y': 
     print 'Not confirmed. Execution terminated.' 
     return 
    id_list = ['id1', 'id2', 'id3'] # or anyhow evaluate the list 
    fill_with_ids(id_list, input_file, output_file) 
    print 'Processed.' 


def main(): 
    launch('input.txt', 'output.txt') 


if __name__ == '__main__': 
    main() 
相關問題