file writing
strings in files
newline in file
text processing
Python file handling

Writing string to a file on a new line every time

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Writing each string on a new line requires appending a newline character (\n) after each string. In Python, the simplest approach is using print() with a file argument (it adds \n automatically) or write() with an explicit \n. Other languages follow similar patterns. The key is understanding whether your write function adds a newline for you or whether you need to add it manually.

Python

Using write() with \n

python
1lines = ["First line", "Second line", "Third line"]
2
3with open("output.txt", "w") as f:
4    for line in lines:
5        f.write(line + "\n")
6
7# output.txt:
8# First line
9# Second line
10# Third line

Using print() with file parameter

python
1lines = ["First line", "Second line", "Third line"]
2
3with open("output.txt", "w") as f:
4    for line in lines:
5        print(line, file=f)  # print adds \n automatically

Using writelines()

python
1lines = ["First line", "Second line", "Third line"]
2
3with open("output.txt", "w") as f:
4    f.writelines(line + "\n" for line in lines)
5
6# Note: writelines() does NOT add newlines — you must add them yourself

Joining with newlines

python
1lines = ["First line", "Second line", "Third line"]
2
3with open("output.txt", "w") as f:
4    f.write("\n".join(lines) + "\n")

Appending to an existing file

python
with open("output.txt", "a") as f:  # "a" for append mode
    f.write("New line appended\n")

JavaScript (Node.js)

javascript
1const fs = require('fs');
2
3const lines = ["First line", "Second line", "Third line"];
4
5// Write all lines at once
6fs.writeFileSync("output.txt", lines.join("\n") + "\n");
7
8// Append line by line
9for (const line of lines) {
10    fs.appendFileSync("output.txt", line + "\n");
11}
12
13// Using streams for large files
14const stream = fs.createWriteStream("output.txt");
15for (const line of lines) {
16    stream.write(line + "\n");
17}
18stream.end();

Java

java
1import java.io.*;
2import java.nio.file.*;
3import java.util.List;
4
5public class FileWriter {
6    public static void main(String[] args) throws IOException {
7        List<String> lines = List.of("First line", "Second line", "Third line");
8
9        // Method 1: Files.write (simplest)
10        Files.write(Path.of("output.txt"), lines);
11        // Writes each string on a new line automatically
12
13        // Method 2: BufferedWriter
14        try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter("output.txt"))) {
15            for (String line : lines) {
16                writer.write(line);
17                writer.newLine();  // Platform-specific newline
18            }
19        }
20
21        // Method 3: PrintWriter
22        try (PrintWriter pw = new PrintWriter("output.txt")) {
23            for (String line : lines) {
24                pw.println(line);  // Adds newline automatically
25            }
26        }
27    }
28}

Go

go
1package main
2
3import (
4    "bufio"
5    "os"
6)
7
8func main() {
9    lines := []string{"First line", "Second line", "Third line"}
10
11    file, _ := os.Create("output.txt")
12    defer file.Close()
13
14    writer := bufio.NewWriter(file)
15    for _, line := range lines {
16        writer.WriteString(line + "\n")
17    }
18    writer.Flush()
19}

C#

csharp
1using System.IO;
2
3string[] lines = { "First line", "Second line", "Third line" };
4
5// Write all lines (adds newline after each)
6File.WriteAllLines("output.txt", lines);
7
8// Append a single line
9File.AppendAllText("output.txt", "New line\n");
10
11// Using StreamWriter
12using (var writer = new StreamWriter("output.txt"))
13{
14    foreach (var line in lines)
15    {
16        writer.WriteLine(line);  // Adds newline automatically
17    }
18}

Platform-Specific Newlines

python
1import os
2
3# os.linesep gives the platform-specific line ending
4# Windows: "\r\n"
5# Linux/Mac: "\n"
6
7with open("output.txt", "w") as f:
8    f.write("Line 1" + os.linesep)
9    f.write("Line 2" + os.linesep)
10
11# However, Python's text mode handles this automatically:
12# Writing "\n" in text mode produces the correct platform newline
13# Only use os.linesep when writing in binary mode ("wb")

Common Pitfalls

  • Forgetting that writelines() does not add newlines: Python's writelines() writes each element exactly as-is without inserting newlines between them. You must append \n to each string yourself, or the entire output ends up on one line.
  • Extra blank line at the end: Writing "\n".join(lines) + "\n" adds a trailing newline. Some tools expect no trailing newline. Omit the + "\n" if the file should not end with a blank line.
  • Using "w" mode when you meant "a": Opening a file with "w" truncates it to zero length before writing. Use "a" (append) to add to an existing file without erasing its contents.
  • Mixing \n and os.linesep in text mode: In Python's text mode, \n is automatically translated to the platform line ending. Using os.linesep in text mode on Windows produces \r\r\n (double carriage return). Use \n in text mode and os.linesep only in binary mode.
  • Not closing the file / not using with: Forgetting to close a file (or not using a with statement) can leave data in the write buffer unflushed. The last few lines may be lost if the program crashes before the buffer is flushed.

Summary

  • Use f.write(line + "\n") or print(line, file=f) in Python
  • writelines() does not add newlines — you must add them manually
  • Use "a" mode to append without overwriting the file
  • Use \n in text mode (Python translates it to the platform line ending)
  • In Java, Files.write(path, lines) and PrintWriter.println() handle newlines automatically
  • Always use with statements or try-finally to ensure files are properly closed and flushed

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.