0

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?

4
  • And what does print repr(x) look like? All print >> fobj does is write to a different file object instead of sys.stdout so the output is exactly the same for both methods. Commented May 20, 2014 at 17:53
  • 1
    Are you using correct line breaks? For example stdout will make a new line for \n (and most of text editors) but notepad.exe( windows) won't, it does just for "\r\n". Commented May 20, 2014 at 17:57
  • print repr(x) looks like one single line, with line breaks as \n included. When I write to the text file, I don't see the line breaks, I just see a space where line breaks should be, a la: "top of table bottomoftable". Commented May 20, 2014 at 18:05
  • 1
    See @at0ma comment. I most definitely bet on an end-of-line issue between terminal and windows notepad, or something nasty like that Commented May 20, 2014 at 18:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nevermind, does work when opened in Notepad++. Thanks!
@user1566200 This is a line-ending issue. Windows' notepad breaks lines only with \r\n, and you're feeding it a file with \n only. Subtle!
@FilipeGonçalves Python may convert '\n' characters to a platform-specific representation on writing and back on reading. See here: python doc

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.