user1566200
user1566200

Reputation: 1838

Print to file in Python?

I've looked at tutorials on how to print to a file in Python, but I'm still have a problem. When I do:

x = a_function_that_spits_out_a_table
print x

The table looks great and is formatted properly. But when I do:

f=open(myfile,"w")
print >> f, x

I get a file with one line of text, without any line breaks. How do I print to a file exactly as how it appears when I use the print command?

Upvotes: 0

Views: 591

Answers (1)

user3657779
user3657779

Reputation:

it would work:

print  >> f, "{line_content} \n".format(line_content=x)

format string method is easy to use.

See doc: format method

Note: Even though I've written new line character as "\n", Python may convert '\n' characters to a platform-specific representation on writing and back on reading. See here: python doc

Upvotes: 2

Related Questions