如何在python3中的文件中写入函数输出

假设我有一类函数

class A:
    def func1():
        print(output.of.api)

    def func2():
        print(output.of.another.api)

#i make the required objects

func1_object = A()
func1_object.func1()

我需要将这些对象的输出写入file.txt

所以我这样做

f = open("file.txt","w")
f.write(func1_object.func())

显然给我一个

的错误
TypeError: write() argument must be str,not None

我尝试了基本的Google解决方案,但这些解决方案显然对我不起作用

提前感谢您的帮助!

lwcxyw 回答:如何在python3中的文件中写入函数输出

func()不返回任何内容。您必须返回输出。

class A:
    def func1():
        return output.of.api

    def func2():
        return output.of.another.api
,
class A:
    def func1():
        with open('file.txt','w') as f:
            print(str(output.of.api),file=f)

或返回值并按照@rbcvi建议将其写入文件

,
class A:
    def func1():
        return output.of.api

with open('file.txt','w') as f:
    f.write((func1_object.func())

当前,您的函数未返回任何内容。

本文链接:https://www.f2er.com/3081099.html

大家都在问