簡體   English   中英

如何在python3的文件中編寫function output

[英]how to write a function output in a file in python3

假設我有一個 class 的功能

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

我需要將這些對象的 output 寫入 file.txt

所以我這樣做

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

這顯然給了我一個錯誤

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

我嘗試了基本的谷歌解決方案,顯然對我不起作用

提前感謝您幫助我!

func()不返回任何內容。 您必須退回您的 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)

或按照@rbcvi 的建議返回值並寫入文件

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

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

目前您的 function 不返回任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM