File Operations
File Read/Write
Python File Operations
Basic File Read/Write
python
# Python - Writing to a file
# Writing to a text file
with open('example.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\\n")
f.write("This is the second line\\n")
f.write("Python file operations example\\n")
# Appending content
with open('example.txt', 'a', encoding='utf-8') as f:
f.write("This is appended content\\n")
# Reading a file
# Reading the entire file
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print("Entire file content:")
print(content)
# Reading line by line
with open('example.txt', 'r', encoding='utf-8') as f:
print("Reading line by line:")
for line in f:
print(f"Line: {line.strip()}")
# Reading all lines into a list
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print("All lines:")
for i, line in enumerate(lines, 1):
print(f"Line {i}: {line.strip()}")Binary File Operations
python
# Python - Binary file operations
# Writing to a binary file
data = b"Hello, Binary World!"
with open('example.bin', 'wb') as f:
f.write(data)
# Reading a binary file
with open('example.bin', 'rb') as f:
binary_data = f.read()
print(f"Binary data: {binary_data}")
print(f"Converted to string: {binary_data.decode('utf-8')}")
# Copying a file
def copy_file(source, destination):
with open(source, 'rb') as src:
with open(destination, 'wb') as dst:
dst.write(src.read())
copy_file('example.txt', 'example_copy.txt')JSON File Operations
python
# Python - JSON file operations
import json
# Writing to a JSON file
data = {
"name": "Alice",
"age": 25,
"city": "New York",
"hobbies": ["reading", "coding", "traveling"],
"is_student": True
}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# Reading a JSON file
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print("JSON data:")
print(json.dumps(loaded_data, ensure_ascii=False, indent=2))
# Appending JSON data
def append_json_data(filename, new_data):
try:
with open(filename, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
except FileNotFoundError:
existing_data = []
if isinstance(existing_data, list):
existing_data.append(new_data)
else:
existing_data = [existing_data, new_data]
with open(filename, 'w', encoding='utf-8') as f:
json.dump(existing_data, f, ensure_ascii=False, indent=2)
append_json_data('data.json', {"name": "Bob", "age": 30})CSV File Operations
python
# Python - CSV file operations
import csv
# Writing to a CSV file
data = [
['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
with open('people.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
# Reading a CSV file
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(f"Row: {row}")
# Reading/writing CSV with dictionaries
people_data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
# Writing dictionary data
with open('people_dict.csv', 'w', newline='', encoding='utf-8') as f:
fieldnames = ['name', 'age', 'city']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(people_data)
# Reading dictionary data
with open('people_dict.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"Name: {row['name']}, Age: {row['age']}, City: {row['city']}")JavaScript File Operations
Basic File Operations (Node.js)
javascript
// JavaScript - File operations (Node.js)
import { promises as fs } from "fs";
// Writing a file
async function writeFile() {
try {
await fs.writeFile(
"example.txt",
"Hello, World!\\nThis is the second line\\nJavaScript file operations example\\n",
"utf-8"
);
console.log("File written successfully");
} catch (error) {
console.error("Failed to write file:", error);
}
}
// Appending content
async function appendFile() {
try {
await fs.appendFile("example.txt", "This is appended content\\n", "utf-8");
console.log("Content appended successfully");
} catch (error) {
console.error("Failed to append content:", error);
}
}
// Reading a file
async function readFile() {
try {
const content = await fs.readFile("example.txt", "utf-8");
console.log("Entire file content:");
console.log(content);
// Reading line by line
const lines = content.split("\\n");
console.log("Reading line by line:");
lines.forEach((line, index) => {
if (line.trim()) {
console.log(`Line ${index + 1}: ${line}`);
}
});
} catch (error) {
console.error("Failed to read file:", error);
}
}
// Execute file operations
async function main() {
await writeFile();
await appendFile();
await readFile();
}
main();Binary File Operations
javascript
// JavaScript - Binary file operations
import { promises as fs } from "fs";
// Writing a binary file
async function writeBinaryFile() {
try {
const data = Buffer.from("Hello, Binary World!", "utf-8");
await fs.writeFile("example.bin", data);
console.log("Binary file written successfully");
} catch (error) {
console.error("Failed to write binary file:", error);
}
}
// Reading a binary file
async function readBinaryFile() {
try {
const binaryData = await fs.readFile("example.bin");
console.log(`Binary data: ${binaryData}`);
console.log(`Converted to string: ${binaryData.toString("utf-8")}`);
} catch (error) {
console.error("Failed to read binary file:", error);
}
}
// Copying a file
async function copyFile(source, destination) {
try {
const data = await fs.readFile(source);
await fs.writeFile(destination, data);
console.log("File copied successfully");
} catch (error) {
console.error("Failed to copy file:", error);
}
}
writeBinaryFile();
readBinaryFile();
copyFile("example.txt", "example_copy.txt");JSON File Operations
javascript
// JavaScript - JSON file operations
import { promises as fs } from "fs";
// Writing to a JSON file
async function writeJsonFile() {
const data = {
name: "Alice",
age: 25,
city: "New York",
hobbies: ["reading", "coding", "traveling"],
is_student: true,
};
try {
await fs.writeFile("data.json", JSON.stringify(data, null, 2), "utf-8");
console.log("JSON file written successfully");
} catch (error) {
console.error("Failed to write JSON file:", error);
}
}
// Reading a JSON file
async function readJsonFile() {
try {
const content = await fs.readFile("data.json", "utf-8");
const loadedData = JSON.parse(content);
console.log("JSON data:");
console.log(JSON.stringify(loadedData, null, 2));
} catch (error) {
console.error("Failed to read JSON file:", error);
}
}
writeJsonFile();
readJsonFile();CSV File Operations
javascript
// JavaScript - CSV file operations
import { promises as fs } from "fs";
import { stringify } from "csv-stringify";
import { parse } from "csv-parse";
// Writing to a CSV file
async function writeCsvFile() {
const data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"],
];
stringify(data, (err, output) => {
if (err) throw err;
fs.writeFile("people.csv", output, "utf-8");
});
}
// Reading a CSV file
async function readCsvFile() {
const content = await fs.readFile("people.csv", "utf-8");
parse(content, (err, records) => {
if (err) throw err;
console.log(records);
});
}
writeCsvFile();
readCsvFile();Path and Directory Operations
Python os and pathlib
python
# Python - Path and directory operations
import os
from pathlib import Path
# Get current directory
print(f"Current dir (os): {os.getcwd()}")
print(f"Current dir (pathlib): {Path.cwd()}")
# Create directory
os.makedirs("test_dir/subdir", exist_ok=True)
Path("test_dir2/subdir2").mkdir(parents=True, exist_ok=True)
# List directory contents
print(f"Contents of test_dir: {os.listdir('test_dir')}")
for item in Path("test_dir2").iterdir():
print(f"Item in test_dir2: {item}")
# Check if path exists
print(f"Does test_dir exist? {os.path.exists('test_dir')}")
print(f"Does test_dir2 exist? {Path('test_dir2').exists()}")
# Join paths
print(f"Joined path (os): {os.path.join('test_dir', 'file.txt')}")
print(f"Joined path (pathlib): {Path('test_dir2') / 'file.txt'}")
# Get basename and dirname
path = "/path/to/some/file.txt"
print(f"Basename: {os.path.basename(path)}")
print(f"Dirname: {os.path.dirname(path)}")
print(f"Pathlib name: {Path(path).name}")
print(f"Pathlib parent: {Path(path).parent}")JavaScript path and fs
javascript
// JavaScript - Path and directory operations
import path from "path";
import { promises as fs } from "fs";
// Get current directory
console.log(`Current dir: ${process.cwd()}`);
// Create directory
fs.mkdir("test_dir/subdir", { recursive: true });
// List directory contents
fs.readdir("test_dir").then((files) => {
console.log(`Contents of test_dir: ${files}`);
});
// Check if path exists
fs.access("test_dir")
.then(() => console.log("test_dir exists"))
.catch(() => console.log("test_dir does not exist"));
// Join paths
console.log(`Joined path: ${path.join("test_dir", "file.txt")}`);
// Get basename and dirname
const filePath = "/path/to/some/file.txt";
console.log(`Basename: ${path.basename(filePath)}`);
console.log(`Dirname: ${path.dirname(filePath)}`);Comparison
| Feature | Python | JavaScript (Node.js) |
|---|---|---|
| Read File | open().read() | fs.readFile() |
| Write File | open().write() | fs.writeFile() |
| Path Operations | os.path, pathlib | path module |
| JSON | json module | JSON.parse, JSON.stringify |
| CSV | csv module | csv-parse, csv-stringify |
| Sync vs. Async | Sync by default | Async by default (Promise-based) |
Exercises
- Write a script to read a text file and count the number of words.
- Create a JSON file and then read and modify one of its values.
- Write a script that lists all files in the current directory.
Next Steps
Now you know how to handle file operations. Next, we'll learn about object-oriented programming.