How to write to a new line every time in python?

io, python

Solution

You have an issue with indentation:

  with open("myNewFile", "a") as file:
  file.write('\n')
  file.write("\n" + status.text + "\n")
  file.write('\n')

If you want to be inside the `with` context, you should indent the following three lines to the right.

Further, you can use `format()` to prepare the string you want to write, for efficiency and readibility:

  import os
  with open("myNewFile", "a") as file:
      file.write('{0}{0} {1} {0}{0}'.format(os.linesep, status.text)
      #file.write('\n')
      #file.write("\n" + status.text + "\n")
      #file.write('\n')

Note the `os.linesep` to insert an OS independent new line :).

You can also write two `linesep` by repeating them twice (multiply the string by 2):

file.write('{0} {1} {0}'.format(os.linesep * 2, status.text)

Which is cleaner.

Problem

I'm just trying to append new tweets that come in to a new line in a file.... So far nothing i'm trying works on OS X Python. ``` class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): print status.text with open("myNewFile", "a") as file: file.write('\n') file.write("\n" + status.text + "\n") file.write('\n') ``` Any ideas?

Original source