使条件成立并将其作为参数传递

时间:2017-02-07 13:06:16

标签: python

我有一个函数,我在文件中写一些东西,如下所示。

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)

我希望在将lin1编写为:

时添加另一个参数
lin1.write(a + " " + id + " " + y/n)

但是y / n应该来自用户输入。此用户输入应该提到第二个函数afucn()

示例:

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

如果我按y,则应将y添加为lin1,如果按n,则应将n添加到lin1作为参数。

1 个答案:

答案 0 :(得分: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()