如何将函数与 python 中的列表组合?

How to combine function with a list in python?

我想合并 out_fun() 到 combinefiles()。目前我有它 out_fun() 它写入 file3.txt 然后关闭它。接下来,我在 combinefiles() 中调用 out_fun() 以编写“Hello World”,以便将 out_fun() 与 combinefiles() 组合。此解决方案不起作用,因为它最终在 Python Shell 中打印了三次 hello world,并在 file3.txt 文件中仅显示“None”。我想知道我该怎么做才能做到这一点,所以它不会打印“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()

我想这就是您要找的东西。 with open(file_path, "a") 如果您想在每次 运行 代码时继续添加到文本文件的底部。否则只需使用 w with 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))