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

问题描述

我想将 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() 的底部。我不能使用 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 时,您通常不需要明确关闭文件。
  • 记住打印值(将其作为字符串发送到控制台)和返回值(使用代码中的实际值)之间的区别