JS
PY

JavaScript to Python

10 lessons

Progress0%
1Variables and Constants2Functions3Arrays vs Lists4Objects vs Dictionaries5Classes and OOP6Modules and Imports7Array Methods vs Comprehensions8Error Handling9Async Programming10File I/O
All Mirror Courses
JS
PY
File I/O
MirrorLesson 10 of 10
Lesson 10

File I/O

Reading and writing files

Introduction

In this lesson, you'll learn about file i/o in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
JS
From JavaScript:

In JavaScript, you're familiar with reading and writing files.

PY
In Python:

Python has its own approach to reading and writing files, which we'll explore step by step.

The Python Way

Let's see how Python handles this concept. Here's a typical example:

PY
Python Example
from pathlib import Path

# Read (context manager ensures file is closed)
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()           # entire file
    # lines = f.readlines()      # list of lines
    # for line in f: ...         # iterate lines

# Write
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello!")

# Append
with open("log.txt", "a") as f:
    f.write("New log entry\n")

# Path manipulation (pathlib)
base  = Path(__file__).parent
full  = base / "data" / "file.txt"
text  = full.read_text(encoding="utf-8")  # shortcut

Comparing to JavaScript

Here's how you might have written similar code in JavaScript:

JS
JavaScript (What you know)
import { readFileSync, writeFileSync, readFile } from "fs";
import { readFile as readFileAsync } from "fs/promises";
import path from "path";

// Sync read
const content = readFileSync("data.txt", "utf-8");

// Async read (callback)
readFile("data.txt", "utf-8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Async read (promise)
const data = await readFileAsync("data.txt", "utf-8");

// Write
writeFileSync("out.txt", "Hello!", "utf-8");

// Path manipulation
const full = path.join(__dirname, "data", "file.txt");
Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

with open() auto-closes the file — always use it

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

pathlib.Path is more readable than path.join()

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Mode 'r'=read, 'w'=write (overwrite), 'a'=append

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

No callback-based API — sync by default; use aiofiles for async

Step-by-Step Breakdown

1. Context Manager (with)

The with statement automatically closes the file when the block exits, even if an error occurs.

JS
JavaScript
const f = fs.readFileSync("file.txt", "utf-8");
PY
Python
with open("file.txt", "r") as f:
    data = f.read()
Rule of Thumb
Always use with open() — never open files without a context manager.

2. pathlib vs path.join

pathlib.Path uses / operator for joining paths and has many convenience methods.

JS
JavaScript
path.join(__dirname, "data", "file.txt")
PY
Python
Path(__file__).parent / "data" / "file.txt"

3. File Modes

Python open() mode strings: 'r' read, 'w' write (truncate), 'a' append, 'b' binary, 'x' exclusive create.

JS
JavaScript
// readFileSync / writeFileSync / appendFileSync
PY
Python
open("f","r")  # read
open("f","w")  # write/overwrite
open("f","a")  # append
open("f","rb") # binary read
Common Pitfall
'w' mode truncates the file! Use 'a' if you want to add to an existing file.

Common Mistakes

When coming from JavaScript, developers often make these mistakes:

  • with open() auto-closes the file — always use it
  • pathlib.Path is more readable than path.join()
  • Mode 'r'=read, 'w'=write (overwrite), 'a'=append
Common Pitfall
Don't assume Python works exactly like JavaScript. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • with open() auto-closes — always use it
  • pathlib.Path for clean path operations
  • 'r','w','a','b' modes
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your JavaScript code in Python to practice these concepts.
PreviousFinish