在 python 中关闭文件后函数调用错误

function call error after closing a file in python

这是我的第一个问题,很抱歉,如果我没有用更少的话表达清楚。 我正在编写一个 python 脚本,我在其中要求用户输入他想要执行的操作。我有两个特定操作的函数(A 和 N)。 我使用 if-else 语句来检查和应用特定函数并将整个输出写入新文件。关闭文件句柄后,我在同一复选框 (if-else) 中调用另一个函数。 about() 根据 if-else 检查,它的输出应该显示在命令提示符上,但我得到

    "Value error: I/O operation on closed file."

这是我目前所做的

    obj = PhysioCal()
if (args.operation == 'N' or args.operation == 'n'):
    with open (args.output,"w") as fout:
        sys.stdout=fout
        t_n=obj.nucleotide(obj.fasta_reader(args.input))
        sys.stdout.close()
    obj.about(t_n)
elif (args.operation == 'A' or args.operation == 'a'):
    with open (args.output,"w") as fout:
        sys.stdout=fout
        t_a=obj.amino_acid(obj.fasta_reader(args.input))
        sys.stdout.close()
    obj.about(t_a)
else:
    obj.about(0)
    print("\n\t\t\tProcess Failed")
    print("\t\t\aYou have seleccted wrong operation")
    print("\t\tuse -h argument for help menu")

此处t_nt_a是函数return的时间。 关于函数在命令提示符下显示时间。

也是在文件中获取函数所有输出而不是在 cmd 上打印的写入方式吗?

由于您 reasigned sys.stdoutfout 然后关闭它,程序无法再打印到标准输出。您可以直接使用 fout 而无需重新分配来写入它。查看 python 文档以写入文件。