I want to append a newline to my string every time I call file.write()
. What's the easiest way to do this in Python?
20 Answers
-
9If you're using variables to compose the record, you can add + "\n" at the end, like fileLog.write(var1 + var2 + "\n"). – Filipe Jul 17 '19 at 02:57
-
21In newer versions of Python (3.6+) you can also just use f-strings: `file.write(f"{var1}\n")` – halfdan Jul 17 '19 at 08:25
-
Or file.write(f'{var1}\n') with single quotation marks – Timo Dec 04 '20 at 19:10
-
what if we need a callback? – mckenzm Nov 07 '21 at 23:00
-
Use '\\n' to write actual '\n' if needed. – Alex Martian Jul 27 '23 at 11:18
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

- 951,095
- 183
- 1,149
- 1,285
-
i am using f.writelines(str(x)) to write into a file where x is list to now tell how to write a list x into a file coping each list starting at new line – kaushik May 27 '10 at 04:47
-
3
-
I think the f.write method is better as it can be used in both Python 2 and 3. – Dang Manh Truong Apr 10 '18 at 12:02
-
3you may use the usage,for example,when you write a int to a file,you can use ***file.write(str(a)+'\n')*** – sixsixsix May 04 '17 at 06:43
-
1@xikhari Why? `file.write(f"my number is: {number}\n")` is just fine and readable. – Guimoute Nov 27 '19 at 15:07
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.

- 1,607
- 1
- 16
- 24
-
3You don't need to `return None` in this case because first, you don't need it and second, every Python function returns `None` by default when there is no `return` statement. – Anna Sep 27 '19 at 14:19
-
1this is a great solution, and honestly `file` should take it as an argument, applied while the file is open. – ekydfejj Nov 06 '20 at 23:15
you could do:
file.write(your_string + '\n')
as suggested by another answer, but why using string concatenation (slow, error-prone) when you can call file.write
twice:
file.write(your_string)
file.write("\n")
note that writes are buffered so it amounts to the same thing.

- 137,073
- 23
- 153
- 219
Another solution that writes from a list using fstring
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
And as a function
def write_list(fname, lines):
with open(fname, "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
write_list('filename.txt', ['hello','world'])

- 4,918
- 3
- 38
- 39
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")

- 12,525
- 8
- 64
- 85
-
5Opening a file with "a" as a parameter instead of "w" doesn't change write to function to work in the way in which you described. The only effect it has is that the file won't be overwritten and text will be added to the bottom-most line instead of starting at the top left of a blank file. – democidist Mar 11 '18 at 21:17
Unless write to binary files, use print. Below example good for formatting csv files:
def write_row(file_, *columns):
print(*columns, sep='\t', end='\n', file=file_)
Usage:
PHI = 45
with open('file.csv', 'a+') as f:
write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
write_row(f) # additional empty line
write_row(f, data[0], data[1])
You can also use partial as a more pythonic way of creating this kind of wrappers. In the example below, row
is print
with predefined kwargs.
from functools import partial
with open('file.csv', 'a+') as f:
row = partial(print, sep='\t', end='\n', file=f)
row('header', 'phi:', PHI, 'serie no. 2', end='\n\n')
row(data[0], data[1])
Notes:
- print documentation
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/, PEP-3101- '\t' - tab character
*columns
in function definition - dispatches any number of arguments to list - see question on *args & **kwargs

- 1,254
- 13
- 21
Just a note, file
isn't supported in Python 3
and was removed. You can do the same with the open
built-in function.
f = open('test.txt', 'w')
f.write('test\n')

- 23,311
- 18
- 141
- 164
Ok, here is a safe way of doing it.
with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('\n')
This writes 1 to 10 each number on a new line.

- 67
- 1
- 3
- 8
I really didn't want to type \n
every single time and @matthause's answer didn't seem to work for me, so I created my own class
class File():
def __init__(self, name, mode='w'):
self.f = open(name, mode, buffering=1)
def write(self, string, newline=True):
if newline:
self.f.write(string + '\n')
else:
self.f.write(string)
And here it is implemented
f = File('console.log')
f.write('This is on the first line')
f.write('This is on the second line', newline=False)
f.write('This is still on the second line')
f.write('This is on the third line')
This should show in the log file as
This is on the first line
This is on the second lineThis is still on the second line
This is on the third line

- 458
- 5
- 18
This is the solution that I came up with trying to solve this problem for myself in order to systematically produce \n's as separators. It writes using a list of strings where each string is one line of the file, however it seems that it may work for you as well. (Python 3.+)
#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
line = 0
lines = []
while line < len(strList):
lines.append(cheekyNew(line) + strList[line])
line += 1
file = open(file, "w")
file.writelines(lines)
file.close()
#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
if line != 0:
return "\n"
return ""

- 105
- 1
- 6
-
Why not simply `with open(path, "w") as file: for line in strList: file.write(line + "\n")`? This way you can remove all the list work, the check, and have just 3 lines. – Guimoute Nov 27 '19 at 15:11
You can decorate method write in specific place where you need this behavior:
#Changed behavior is localized to single place.
with open('test1.txt', 'w') as file:
def decorate_with_new_line(method):
def decorated(text):
method(f'{text}\n')
return decorated
file.write = decorate_with_new_line(file.write)
file.write('This will be on line 1')
file.write('This will be on line 2')
file.write('This will be on line 3')
#Standard behavior is not affected. No class was modified.
with open('test2.txt', 'w') as file:
file.write('This will be on line 1')
file.write('This will be on line 1')
file.write('This will be on line 1')

- 21
- 4
Using append (a)
with open()
on a print()
statement looks easier for me:
save_url = ".\test.txt"
your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))
another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))
another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))

- 834
- 8
- 8
You could use C-style string formatting:
file.write("%s\n" % "myString")
More about String Formatting.

- 41
- 3
Usually you would use \n
but for whatever reason in Visual Studio Code 2019 Individual it won't work. But you can use this:
# Workaround to \n not working
print("lorem ipsum", file=f) # Python 3.0 onwards only
print >>f, "Text" # Python 2.0 and under

- 44,374
- 10
- 104
- 119

- 101
- 8
If you know in advance which lines to add, you can do so:
with open(file_path, 'w') as f:
text = "\n".join(lines_list)
f.write(text)

- 603
- 7
- 8
If write is a callback, you may need a custom writeln.
def writeln(self, string):
self.f.write(string + '\n')
Itself inside a custom opener. See answers and feedback for this question : subclassing file objects (to extend open and close operations) in python 3
(Context Manager)
I faced this when using ftplib to "retrieve lines" from a file that was "record based" (FB80):
with open('somefile.rpt', 'w') as fp:
ftp.retrlines('RETR USER.REPORT', fp.write)
and ended up with one long record with no newlines, this is likely a problem with ftplib, but obscure.
So this became:
with OpenX('somefile.rpt') as fp:
ftp.retrlines('RETR USER.REPORT', fp.writeln)
It does the job. This is a use case a few people will be looking for.
Complete declaration (only the last two lines are mine):
class OpenX:
def __init__(self, filename):
self.f = open(filename, 'w')
def __enter__(self):
return self.f
def __exit__(self, exc_type, exc_value, traceback):
self.f.close()
def writeln(self, string):
self.f.write(string + '\n')

- 1,545
- 1
- 12
- 19
in order to suspport multiple operating systems use:
file.write(f'some strings and/or {variable}. {os.linesep}')

- 464
- 4
- 6
Actually, when you use the multiline syntax, like so:
f.write("""
line1
line2
line2""")
You don't need to add \n
!

- 36
- 2
- 7