Write a String to a File on a New Line every time in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Write a string to a file on a new line every time in Python
  2. Adding the newline character directly into the string
  3. Using a for loop to write a list of strings to a file on new lines
  4. Write a string to a file on a new line every time using join()
  5. The issues around using the older open() syntax

# Write a string to a file on a new line every time in Python

To write a string to a file on a new line every time:

  1. Open the file in writing mode.
  2. Append a newline (\n) character to the end of each string.
  3. Use the file.write() method to write the lines to the file.
main.py
# ✅ 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()

write string to file on new line every time

If you run the code sample, you'd create an example.txt file with the following contents.

example.txt
first line second line third line
The code for this article is available on GitHub

We used the with statement to open the file in reading mode.

The statement automatically takes care of closing the file for us.

The 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.

# Adding the newline character directly into the string

If you are writing string literals to the file, add the \n character directly at the end of each string.

main.py
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')

adding newline character directly into the string

The code for this article is available on GitHub

# Using a formatted string literal instead

Conversely, if you need to interpolate variables in a string, use a formatted string literal.

main.py
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')

using formatted string literal instead

The output looks as follows.

example.txt
First line: bobby Second line: hadz Third line: com
The code for this article is available on GitHub

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

# Using a for loop to write a list of strings to a file on new lines

Use a for loop if you need to write a list of strings to a file on a new line every time.

main.py
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')

using for loop to write list of strings on new lines

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.

# Defining a reusable function

If you have to do this often, define a reusable function.

main.py
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'] )

defining reusable function

The code for this article is available on GitHub

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.

# Write a string to a file on a new line every time using join()

You can also use the str.join() method to write a string to a file on a new line every time.

main.py
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 code for this article is available on GitHub

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a 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().

main.py
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.

# The issues around using the older open() syntax

You can also use the older syntax that requires you to manually close the file.

main.py
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 for this article is available on GitHub

The code sample writes the strings to the file on new lines, however, we have to manually close the file after we're done.

This is an issue because if an error is raised before the 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.