Last updated: Apr 10, 2024
Reading time·4 min
To write a string to a file on a new line every time:
\n
) character to the end of each string.file.write()
method to write the lines to the file.# ✅ Newer syntax (better) with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n') # ----------------------------------------------------- # ✅ Older syntax (not recommended) file = open('example.txt', 'w', encoding='utf-8') file.write('first line' + '\n') file.write('second line' + '\n') file.write('third line' + '\n') file.close()
If you run the code sample, you'd create an example.txt
file with the
following contents.
first line second line third line
We used the with statement to open the file in reading mode.
The statement automatically takes care of closing the file for us.
file.write()
method takes a string and writes the contents of the string to the file.We used the addition (+) operator
to add a newline (\n
) character to the end of each line.
If you are writing string literals to the file, add the \n
character directly
at the end of each string.
with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write('bobby\n') my_file.write('hadz\n') my_file.write('com\n')
Conversely, if you need to interpolate variables in a string, use a formatted string literal.
with open('example.txt', 'w', encoding='utf-8') as my_file: var1 = 'bobby' var2 = 'hadz' var3 = 'com' my_file.write(f'First line: {var1}\n') my_file.write(f'Second line: {var2}\n') my_file.write(f'Third line: {var3}\n')
The output looks as follows.
First line: bobby Second line: hadz Third line: com
Formatted string literals
(f-strings) let us include expressions inside of a string by prefixing the
string with f
.
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces - {expression}
.
Use a for loop if you need to write a list of strings to a file on a new line every time.
with open('example.txt', 'w', encoding='utf-8') as my_file: a_list = ['bobby', 'hadz', 'com'] for item in a_list: my_file.write(f'{item}\n')
We used a for
loop to iterate over the list, added a newline character to the
end of each item and wrote the result to a file.
If you have to do this often, define a reusable function.
def write_on_separate_lines(file_name, lines): with open(file_name, 'w', encoding='utf-8') as file: for line in lines: file.write(f'{line}\n') write_on_separate_lines( 'example.txt', ['bobby', 'hadz', 'com'] )
The function takes a file name and a list of lines as parameters and writes the lines to the file, appending a newline character at the end of each line.
You can also use the str.join()
method to write a string to a file on a new
line every time.
with open('example.txt', 'w', encoding='utf-8') as my_file: a_list = ['bobby', 'hadz', 'com'] a_str = '\n'.join(a_list) my_file.write(f'{a_str}\n')
The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
TypeError
if there are any non-string values in the iterable.If your iterable contains numbers or other types, convert all of the values to
strings before calling join()
.
with open('example.txt', 'w', encoding='utf-8') as my_file: a_list = ['bobby', 1, 'hadz', 2, 'com'] a_str = '\n'.join(map(str, a_list)) my_file.write(f'{a_str}\n')
We joined the strings in the list with a newline separator to write them to a file on separate lines.
You can also use the older syntax that requires you to manually close the file.
file = open('example.txt', 'w', encoding='utf-8') file.write('first line' + '\n') file.write('second line' + '\n') file.write('third line' + '\n') file.close()
The code sample writes the strings to the file on new lines, however, we have to manually close the file after we're done.
file.close()
line runs, we would get a memory leak.On the other hand, the with open()
statement takes care of automatically
closing the file even if an error is raised.
Calling the file.write()
method without using the with
statement or calling
file.close()
might result in the arguments of file.write()
not being
completely written to the disk.
The newer with open()
syntax is a much better option and should be your
preferred approach.
You can learn more about the related topics by checking out the following tutorials: