Python
Coding
File Manipulation
Programming Skills
List Handling

Python: write a list to a file with newlines (write vs writelines)

Codemia Knowledge Hub ·

To write a Python list to a file with one item per line, open the file with open() and either call write(item + "\n") for each item or pass items that already end in "\n" to writelines(). writelines() does not add newlines for you. For large lists, "\n".join(items) lets you write everything in one call.

Writing each item with write()

python
1# A list of items
2items = ['apple', 'banana', 'cherry']
3
4# Open a file and write the list to it
5with open('fruits.txt', 'w') as file:
6    for item in items:
7        file.write(item + "\n")

This code:

  1. Creates a list called items.
  2. Opens fruits.txt in write mode (w). The file is created if it doesn't exist, and its contents are erased if it does.
  3. Writes each item followed by a newline character \n, so every item starts on its own line.

Using writelines() with explicit newlines

Despite its name, writelines() writes the strings exactly as given, so each one must already include its newline:

python
items = ['apple', 'banana', 'cherry']
with open('fruits.txt', 'w') as file:
    file.writelines([item + "\n" for item in items])

The list comprehension appends "\n" to each item before the list is passed to writelines().

Handling file paths and exceptions

Wrap file operations in try/except so an I/O failure doesn't crash the program, and build paths with an absolute or well-defined relative location:

python
1import os
2
3items = ['apple', 'banana', 'cherry']
4path = '/path/to/your/directory'
5filename = 'fruits.txt'
6full_path = os.path.join(path, filename)
7
8try:
9    with open(full_path, 'w') as file:
10        file.writelines([item + "\n" for item in items])
11except IOError:
12    print("An IOError occurred while writing to the file.")

Writing everything in one call with join()

Calling write() once per element can be inefficient for very large lists. Joining the items into one string and writing it once reduces the number of write operations:

python
items = ['apple', 'banana', 'cherry']
with open('fruits.txt', 'w') as file:
    file.write("\n".join(items) + "\n")
MethodDescriptionMemory EfficiencyEase of Use
write()Manually add newlines and write each item individually.Lower for large lists.Moderate
writelines()Auto handles list but requires manual newline chars.ModerateHigh
write() with join()Join all items and write once, adding newlines.HighHigh

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms