如何将函数输出写入文本文件

时间:2021-07-09 11:44:35

标签: python

我正在尝试将函数的输出写入文本文件,但不确定如何执行此操作。我知道如何用变量来做到这一点,这很好用。但是,我无法使用函数解决此问题。

有什么建议吗?

def test():
    device = "PC"
    print(device + " This is an example")
    print("Writing to output")
test()

示例 1

def test():

    f = open("newfile.txt", "a")

    device = "PC"
    print(device + " This is an example")
    print("Writing to output")

    f.write()
    f.close()

问题

TypeError: TextIOWrapper.write() 只需要一个参数(给定 0)

示例 2

def test():

    f = open("newfile.txt", "a")

    device = "PC"
    print(device + " This is an example")
    print("Writing to output")

    f.write(test())
    f.close()

问题

Newfile.txt 已创建,但文件中没有数据。

4 个答案:

答案 0 :(得分:1)

def test():
    device = "PC"
    print("writing to output")
    return device + " This is an example"

with open("newfile.txt", "a") as f:
    f.write(test())

答案 1 :(得分:0)

在第一个例子中,你没有在 write 函数中放置任何东西
放你想要的东西

def test():
    f = open("newfile.txt", "a")
    device = "PC"
    f.write(device + " This is an example")
    f.write("Writing to output")
    f.close()

在第二个函数中,您试图在测试函数中调用测试函数。这是可能的,但它对这里没有兴趣。

如果你想写一个函数的输出,你必须返回这个值才能使用

def test():
    result = ''
    device = "PC"
    result = device + " This is an example"
    result += "Writing to output"

    return result

f = open("newfile.txt", "a")
f.write(test()) 
f.close()

答案 2 :(得分:0)

File_object.write(argument)  

在括号 f.write(device) 中接受一个参数

您在答案的第一部分中缺少参数,该参数应该是您想写入新文件的文本。

完整代码:-

def test():
    device = "PC"
    print("writing to output")
    return device + " This is an example"


f = open("newfile.txt", "a")
f.write(test())
f.close()

答案 3 :(得分:0)

我会这样做:

def test(filename, device):
    print("Writing to output")
    with open(filename, "w") as f:
        f.write(device+" This is an example")

def main():
    test("file.txt", "PC")

if __name__ == "__main__":
    main()

希望有用。 :-)