【发布时间】: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