2
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 ?

3
  • 2
    I suggest that you read: InputOutput Commented May 15, 2015 at 9:11
  • Was there a problem when you ran it? Commented May 15, 2015 at 9:21
  • 1
    In Python 2, you can use print >>file, c to send the output of a print statement to the file. In Python 3 the print() function uses a keyword argument to do this, i.e. print(c, file=file). A file's write() method does not automatically call an object's __str__() method like print does, so you'd need do it explicitly via file.write(str(c)+'\n'). Commented May 15, 2015 at 9:52

1 Answer 1

4

You can use the str() function to convert an object to a string the same way print does:

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 >> file, c
Sign up to request clarification or add additional context in comments.

1 Comment

I'd add a mention to the print_function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.