简体   繁体   English

将python对象__str__写入文件

[英]write python object __str__ to file

class C:
    pass

file = open("newfile.txt", "w")

for j in range(10):
    c = C()
    print c
    file.write(c)

file.close()

Is there anything wrong in this code? 这段代码有什么问题吗?
I am new to python and want to write the content that's outputted by 'print c' to file ? 我是python新手,想将'print c'输出的内容写入文件吗?

You can use the str() function to convert an object to a string the same way print does: 您可以使用str()函数将对象转换为字符串,就像print一样:

for j in range(10):
    c = C()
    print c
    file.write(str(c))

This will not include a newline, however. 但是,这将不包括换行符。 If you need a newline as well, you can manually add one: 如果还需要换行符,则可以手动添加一个换行符:

file.write(str(c) + '\n')

or use string formatting: 或使用字符串格式:

file.write('{}\n'.format(c))

or use the print statement with redirection ( >> fileobject ): 或将print语句与重定向一起使用( >> fileobject ):

print >> file, c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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