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
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.
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:
fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()
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.
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) # newline
write_row(f, data[0], data[1])
Notes:
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/, PEP-3101*columns
in function definition - dispatches any number of arguments to list - see question on *args & **kwargsAnother 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'])
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")
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')
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.
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 ""
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
You can use:
file.write(your_string + '\n')
Source: Stackoverflow.com