如何在python中将函数与列表结合起来?

问题描述

我想将 out_fun() 与 combinefiles() 结合起来。目前我有它 out_fun() 它写入 file3.txt 然后关闭它。接下来,我在 combinefiles() 中调用 out_fun() 来编写“Hello World”,以便将 out_fun() 与 combinefiles() 结合起来。此解决方案不起作用,因为它最终在 Python Shell 中单独打印 hello world 三次,并且在 file3.txt 文件中仅显示“无”。我想知道如何才能做到这一点,所以它不会打印“Hello World”三遍,因为我希望它只像 out_fun() 一样打印一次,然后我想要“Hello World”添加到 combinefiles() 底部

def out_fun(): 
    print("Hello World")
output = out_fun() 
file = open("file3.txt","w") 
file.write(str(output))
file.close() 

def combinefiles():
    filenames = ['file1.txt','file2.txt']
        with open('file3.txt','w') as outfile:
            for names in filenames:
                with open(names) as infile:
                    outfile.write(infile.read())
                    outfile.write("\n")
                    output = out_fun()
                    outfile.write(str(output))
        outfile.close()
combinefiles()

解决方法

我想这就是你要找的东西。如果您想在每次运行代码时继续添加到文本文件的底部,请使用 open(file_path,"a") 。否则只需使用 w 和 open(file_path,"w")

output = "Hello World!"
file_names = ["file1.txt","file2.txt","file3.txt"]
def combine_files(file_names,output):
    for file_path in file_names:
        with open(file_path,"a") as file:
            file.write(output)

        
combine_files(file_names,output)
,

printreturn 关键字之间存在差异。 Print 接受它的参数并将它们转储到标准输出,而 return 从调用函数的地方返回参数。在本例中,它是从 output = out_fun() 调用的。要了解有关差异的更多信息,请查看 this link

def out_fun():
    return "Hello World"

output = out_fun()
file = open("file3.txt","w")
file.write(str(output))
file.close()

def combinefiles():
    filenames = ['file1.txt','file2.txt']
    with open('file3.txt','w') as outfile:
        for names in filenames:
            with open(names) as infile:
                outfile.write(infile.read())
                outfile.write("\n")
        outfile.write(str(output))

combinefiles()

您必须在写入这两个文件后使用 outfile.write(str(output))