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()
This code:
- Creates a list called
items. - Opens
fruits.txtin write mode (w). The file is created if it doesn't exist, and its contents are erased if it does. - 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:
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:
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:
| Method | Description | Memory Efficiency | Ease 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. | Moderate | High |
write() with join() | Join all items and write once, adding newlines. | High | High |
Related reading
- Writing a Python list of lists to a csv file
- Xamarin.Android no stack trace in async method
- Xcode 4.2 debug doesn't symbolicate stack call
- XGBoost - n_estimators 1 equal to single-tree classifier?
- Writing a pandas DataFrame to CSV file
- Writing a pickle file to an s3 bucket in AWS
- XGboost cannot pass validation data for eval_set in pipeline
- xgboost.plot_tree binary feature interpretation
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough

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