Files
Comparison between JavaScript and Python
The information comes from the Udemy course "Become an AI Engineer: Python for JavaScript Developers" by
Vilva Athiban
| Feature |
JavaScript |
Python |
| Read a whole file |
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const content = fs.readFileSync("test.txt", "utf-8");
console.log(content);
|
# Use `with` (a context manager): it auto-closes the file when the block ends,
# even if an exception is raised. No manual close() needed.
with open("test.txt") as f:# default mode is "r" (read)
content = f.read()
print(content)
|
| Write |
Write (overwrites)
fs.writeFileSync("test.txt", "This is new text");
|
Write (mode "w" overwrites; default "r" is read-only)
with open("test.txt", "w") as f: # forgetting "w" -> "not writable" error
f.write("This is new text")
|
| Read line by line |
const lines = fs.readFileSync("test.txt", "utf-8").split("\n");
for (const line of lines) {
console.log(line);
}
|
with open("test.txt") as f:
for line in f: # iterate the file object directly
print(line, end="")
# In Python, file open/read/write/close are all SYNCHRONOUS operations.
|
| Paths |
const __filename = fileURLToPath(import.meta.url);
console.log(path.extname(__filename)); // ".js" (extension)
console.log(path.basename(__filename)); // file name
console.log(path.dirname(__filename)); // parent folder
|
import pathlib
file_path = pathlib.Path(__file__) # __file__ = current file
print(file_path.suffix) # ".py" extension
print(file_path.name) # full file name
print(file_path.stem) # name without extension
print(file_path.parent) # parent folder
print(file_path.absolute()) # absolute path
|