Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将一个普通函数与另一个将不同文本文件合并到一个文件中的函数相结合?_Python_List_Loops_For Loop_With Statement - Fatal编程技术网

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

Python 如何将一个普通函数与另一个将不同文本文件合并到一个文件中的函数相结合?,python,list,loops,for-loop,with-statement,Python,List,Loops,For Loop,With Statement,我想将_fun()合并到combinefile()。目前我有它的where out_fun()写入file3.txt,然后关闭它。接下来,在combinefiles()中调用out\u fun()来编写“Hello World”,以便将out\u fun()与combinefiles()结合起来。此解决方案不起作用,因为它在Python Shell中分别打印hello world三次,并且在file3.txt文件中只显示“None”。我想知道我如何才能做到这一点,这样它就不会打印“Hello W

我想将_fun()合并到combinefile()。目前我有它的where out_fun()写入file3.txt,然后关闭它。接下来,在combinefiles()中调用out\u fun()来编写“Hello World”,以便将out\u fun()与combinefiles()结合起来。此解决方案不起作用,因为它在Python Shell中分别打印hello world三次,并且在file3.txt文件中只显示“None”。我想知道我如何才能做到这一点,这样它就不会打印“Hello World”三次,因为我只想像in-out\u fun()一样打印一次,然后我想将“Hello World”添加到CombineFile()的底部。我无法使用return,因为它在“end=”“”处出现语法错误

预期的文本文件输出在单独的行上:

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

以下是创建所需输出的工作版本:

随机导入
def out_fun():
返回f'您的数字为{random.randint(0,5)}'
打开('file3.txt','w')作为文件:
file.write(out_fun())
def file1():
fileone=input('请告诉我您的名字:')
将open('file1.txt','w')作为fileone\u文件:
fileone_file.write(fileone)
文件1()
def file2():
filetwo=input('请告诉我您最喜欢的颜色:')
将open('file2.txt','w')作为filetwo\u文件:
filetwo\u file.write(filetwo)
文件2()
def combinefiles():
文件名=['file1.txt','file2.txt']
以open('file3.txt','w')作为输出文件:
对于文件名中的名称:
打开(名称)作为填充:
outfile.write(infle.read())
outfile.write(“\n”)
outfile.write(out_fun())
组合文件()
请注意,最后的
outfile.write
调用在
for
循环之外

请注意:

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

  • out\u fun
    函数不返回值,因此
    输出将始终为
    None
    。不要使用
    打印
    。相反,返回字符串
    return f“您的号码是{random.randint(0,5)}”
    @johnymopp谢谢您的工作!但是,当我查看文本文件时,我看到当将数字放入combinefiles()函数时,它会打印两次。您知道一种只能打印一次的解决方案吗?现在您正在使用一个在2元素数组上循环的
    for
    循环,因此循环中的代码将被调用两次。您能更明确地说明您希望输出/结果是什么样子吗?@nullromo我已经编辑了我的代码,并在函数file1和file2中添加了预期的文本文件输出。谢谢。我想这只是一个缩进错误。我贴出了完整的答案。
    John (name)
    Blue (color)
    12 (random number)