2017-02-07 45 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() 
相关问题