简体   繁体   中英

how to write a function output in a file in python3

suppose i have a class of functions

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()

it is required of me to write the output of these objects in a file.txt

So I do this

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

which obviously gives me an error of

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

I have tried basic google solutions which obviously didn't work for me

Thanks in advance for helping me out!

func() doesn't return anything. You have to return your output.

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)

or return the values and write to a file as @rbcvi suggested

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

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

Currently your function doesn't return anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM