Writing string to a file on a new line every time

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

Use "\n":

file.write("My String\n")

See the Python manual for reference.


If you use it extensively (a lot of written lines), you can subclass 'file':

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')

Now it offers an additional function wl that does what you want:

with cfile('filename.txt', 'w') as fid:
    fid.wl('appends newline charachter')
    fid.wl('is written on a new line')

Maybe I am missing something like different newline characters (\n, \r, ...) or that the last line is also terminated with a newline, but it works for me.


You can use:

file.write(your_string + '\n')

Tags:

Python

Newline