【问题标题】:How to combine a normal function with another function that will combine different text files into one file?如何将普通函数与另一个将不同文本文件合并到一个文件中的函数结合起来?
【发布时间】:2026-01-14 15:35:02
【问题描述】:

我想将 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)

【问题讨论】:

  • out_fun 函数没有 return 值,因此 output 将始终为 None。不要使用print。而是返回字符串return f"Your number is {random.randint(0,5)}"
  • @JohnnyMopp 谢谢你的工作!但是,当我查看文本文件时,我看到将数字放入 combinefiles() 函数时会打印两次。你知道一个只能打印一次的解决方案吗?
  • 现在您正在使用 for 循环,该循环在 2 元素数组上循环,因此循环中的代码被调用了两次。您能否更明确地说明您希望输出/结果的样子?
  • @nullromo 我已经编辑了我的代码并添加了函数 file1 和 file2 以及预期的文本文件输出。谢谢。
  • 我认为这只是一个缩进错误。我发布了一个完整的答案。

标签: python list loops for-loop with-statement


【解决方案1】:

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

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

【讨论】:

    最近更新 更多