Reading Files compared across 16 programming languages

Reading and writing files – the introduction to input and output.

Python JavaScript TypeScript Java C C++ C# Go Rust PHP Ruby Swift Kotlin SQL Bash HTML & CSS

PyPython

with open("notizen.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\nLine 2\n")

with open("notizen.txt", encoding="utf-8") as f:
    for zeile in f:
        print(zeile.strip())

with closes the file automatically, even on errors.

JSJavaScript

import { writeFileSync, readFileSync } from "node:fs";

writeFileSync("notizen.txt", "Line 1\nLine 2\n", "utf-8");
const text = readFileSync("notizen.txt", "utf-8");
for (const zeile of text.split("\n")) {
  if (zeile) console.log(zeile);
}

File access exists only in Node.js (with "type": "module" or as .mjs), not in the browser. For large files, use the asynchronous variants from node:fs/promises.

TSTypeScript

import { readFileSync, writeFileSync } from "node:fs";

writeFileSync("notizen.txt", "Line 1\nLine 2\n", "utf-8");
const text: string = readFileSync("notizen.txt", "utf-8");
for (const zeile of text.split("\n")) {
  if (zeile) console.log(zeile);
}

Requires npm install --save-dev @types/node so that TypeScript knows the types of node:fs. Because of the "utf-8" argument, readFileSync returns a string (otherwise a Buffer).

JvJava

import java.io.IOException;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Path datei = Path.of("notizen.txt");
        Files.writeString(datei, "Line 1\nLine 2\n");
        for (String zeile : Files.readAllLines(datei)) {
            System.out.println(zeile.strip());
        }
    }
}

Files from java.nio.file takes care of opening and closing itself. The IOException is checked and is passed on here with throws.

CC

#include <stdio.h>

int main(void) {
    FILE *f = fopen("notizen.txt", "w");
    if (!f) return 1;
    fprintf(f, "Line 1\nLine 2\n");
    fclose(f);

    char zeile[100];
    f = fopen("notizen.txt", "r");
    if (!f) return 1;
    while (fgets(zeile, sizeof zeile, f)) printf("%s", zeile);
    fclose(f);
    return 0;
}

fopen/fclose open and close; fgets reads at most sizeof zeile characters and is therefore safe from buffer overflows. Every fopen needs an fclose.

C++C++

#include <fstream>
#include <iostream>
#include <string>

int main() {
    { std::ofstream out("notizen.txt"); out << "Line 1\nLine 2\n"; }
    std::ifstream in("notizen.txt");
    std::string zeile;
    while (std::getline(in, zeile))
        std::cout << zeile << '\n';
}

The block closes out automatically when left (RAII); only then is the file completely written. getline in the while condition reads line by line until the end of the file.

C#C#

File.WriteAllText("notizen.txt", "Line 1\nLine 2\n");

foreach (string zeile in File.ReadLines("notizen.txt"))
{
    Console.WriteLine(zeile);
}

File.WriteAllText writes the whole file, File.ReadLines reads it line by line in a memory-friendly way. File lives in System.IO (imported automatically via implicit usings).

GoGo

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	_ = os.WriteFile("notizen.txt", []byte("Line 1\nLine 2\n"), 0o644)
	data, err := os.ReadFile("notizen.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.TrimSpace(string(data)))
}

os.WriteFile/os.ReadFile handle small files in one step (without open handles). For large files use os.Open + bufio.Scanner.

RsRust

use std::fs;
use std::io;

fn main() -> io::Result<()> {
    fs::write("notizen.txt", "Line 1\nLine 2\n")?;
    let inhalt = fs::read_to_string("notizen.txt")?;
    for zeile in inhalt.lines() {
        println!("{}", zeile.trim());
    }
    Ok(())
}

fs::write and fs::read_to_string do everything in one line. ? passes I/O errors on to the caller; the file is closed automatically through Drop.

PHPPHP

<?php
file_put_contents("notizen.txt", "Line 1\nLine 2\n");
foreach (file("notizen.txt", FILE_IGNORE_NEW_LINES) as $zeile) {
    echo $zeile, "\n";
}

file_put_contents writes, file reads all lines into an array. For very large files it is better to read with fopen/fgets (or a generator).

RbRuby

File.write("notizen.txt", "Line 1\nLine 2\n")
File.foreach("notizen.txt") do |zeile|
  puts zeile.chomp
end

File.write creates the file, File.foreach reads it line by line (memory-friendly even for large files). chomp removes the line break.

SwSwift

import Foundation

let pfad = "notizen.txt"
do {
    try "Line 1\nLine 2\n".write(toFile: pfad, atomically: true, encoding: .utf8)
    let inhalt = try String(contentsOfFile: pfad, encoding: .utf8)
    for zeile in inhalt.split(separator: "\n") { print(zeile) }
} catch { print("Error:", error) }

File access is part of Foundation. Both calls can throw, hence try inside the do block. In apps you usually use FileManager and URLs.

KtKotlin

import java.io.File

fun main() {
    val datei = File("notizen.txt")
    datei.writeText("Line 1\nLine 2\n")
    datei.forEachLine { println(it.trim()) }
}

Kotlin adds writeText, readText, forEachLine, and more to java.io.File – no need to open and close by hand.

SQLSQL

-- SQLite (sqlite3 shell)
.mode csv
.import produkte.csv produkte_import
.headers on
.output export.csv
SELECT * FROM produkte;
.output stdout

-- PostgreSQL (psql, client-side)
\copy produkte FROM 'produkte.csv' WITH (FORMAT csv, HEADER true)
\copy (SELECT * FROM produkte) TO 'export.csv' WITH (FORMAT csv, HEADER true)

-- MySQL
LOAD DATA LOCAL INFILE 'produkte.csv' INTO TABLE produkte
FIELDS TERMINATED BY ',' IGNORE 1 LINES;

File access is not part of the SQL standard but a matter for the tools: .import (SQLite), COPY or copy (PostgreSQL), LOAD DATA (MySQL). copy runs on the client, COPY on the server and needs file permissions there.

shBash

printf 'Line 1\nLine 2\nLine 3\n' > notizen.txt

nr=0
while IFS= read -r zeile; do
  nr=$((nr + 1))
  echo "$nr: $zeile"
done < notizen.txt

while read … done < file reads line by line. IFS= and -r preserve spaces and backslashes. Important: redirect the file with < instead of cat file | while … – the pipe would create a subshell and variables would be lost.

</>HTML & CSS

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222} img { border-radius: 8px; vertical-align: middle; } figure { margin: 8px 0; }</style>
<!-- Image: alt is mandatory; here a data: URI instead of a file -->
<img width="64" height="64" alt="Blue circle with a star"
     src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='64' height='64'%3E%3Ccircle cx='32' cy='32' r='30' fill='%232b59c3'/%3E%3Ctext x='32' y='42' font-size='30' text-anchor='middle' fill='white'%3E%E2%98%85%3C/text%3E%3C/svg%3E">
<!-- Links: external, internal (anchor), download -->
<p><a href="https://developer.mozilla.org" target="_blank" rel="noopener noreferrer">External link</a> ·
   <a href="#ziel">Jump down</a> ·
   <a href="daten.csv" download>Download CSV</a></p>
<!-- Inline SVG: scalable, stylable with CSS -->
<svg width="60" height="30" role="img" aria-label="Green bar"><rect width="60" height="30" rx="6" fill="seagreen"/></svg>
<p id="ziel" style="margin-top:80px">Here is the anchor <code>#ziel</code>.</p>

You include files by URL: <img src>, <a href>, <link href>, <script src>, <iframe src>. Here a data: URI and inline SVG replace the external file. External links with target="_blank" should also get rel="noopener".

More comparisons

Hello World Variables Conditionals Loops Functions Lists and Arrays Dictionaries and Maps Classes and Objects Error Handling