如何将一个普通函数与另一个将不同文本文件合并到一个文件中的函数结合起来?

How to combine a normal function with another function that will combine different text files into one file?

我想将 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() 的底部。我不能使用 return 因为它在 'end=""'

处给出语法错误
def out_fun(): 
    print("Your number is ", end="")
    print(random.randint(0,5)
output = out_fun() 
file = open("file3.txt","w") 
file.write(str(output))
file.close() 

def file1():
    fileone = input("Please tell me your name: ")
    fileone_file = open("file1.txt", "w")
    a = fileone_file.write(fileone)
    fileone.file.close()
file1()

def file2():
    filetwo = input("Please tell me your favorite color: ")
    filetwo_file = open("file2.txt", "w")
    a = filetwo_file.write(filetwo)
    filetwo.file.close()
file2()

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()

预期的文本文件输出在不同的行上:

John (name)
Blue (color)
12 (random number)

这是一个可以创建所需输出的工作版本:

import random

def out_fun():
    return f'Your number is {random.randint(0,5)}'

with open('file3.txt','w') as file:
    file.write(out_fun())

def file1():
    fileone = input('Please tell me your name: ')
    with open('file1.txt', 'w') as fileone_file:
        fileone_file.write(fileone)
file1()

def file2():
    filetwo = input('Please tell me your favorite color: ')
    with open('file2.txt', 'w') as filetwo_file:
        filetwo_file.write(filetwo)
file2()

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

请注意,最后的 outfile.write 调用是 for 循环之外。

一些注意事项:

  • 您应该更喜欢使用 with 打开文件而不是 open/close
  • 使用 with 时,您通常不需要明确关闭文件。
  • 记住打印值(将其作为字符串发送到控制台)和返回值(使用代码中的实际值)之间的区别