文件操作
文件读写
Python 文件操作
基本文件读写
python
# Python - 写入文件
# 写入文本文件
with open('example.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\n")
f.write("这是第二行\n")
f.write("Python 文件操作示例\n")
# 追加内容
with open('example.txt', 'a', encoding='utf-8') as f:
f.write("这是追加的内容\n")
# 读取文件
# 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print("整个文件内容:")
print(content)
# 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
print("逐行读取:")
for line in f:
print(f"行: {line.strip()}")
# 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print("所有行:")
for i, line in enumerate(lines, 1):
print(f"第{i}行: {line.strip()}")二进制文件操作
python
# Python - 二进制文件操作
# 写入二进制文件
data = b"Hello, Binary World!"
with open('example.bin', 'wb') as f:
f.write(data)
# 读取二进制文件
with open('example.bin', 'rb') as f:
binary_data = f.read()
print(f"二进制数据: {binary_data}")
print(f"转换为字符串: {binary_data.decode('utf-8')}")
# 复制文件
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 文件操作
python
# Python - JSON 文件操作
import json
# 写入 JSON 文件
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)
# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print("JSON 数据:")
print(json.dumps(loaded_data, ensure_ascii=False, indent=2))
# 追加 JSON 数据
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 文件操作
python
# Python - CSV 文件操作
import csv
# 写入 CSV 文件
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)
# 读取 CSV 文件
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(f"行: {row}")
# 使用字典读写 CSV
people_data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
# 写入字典数据
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)
# 读取字典数据
with open('people_dict.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"姓名: {row['name']}, 年龄: {row['age']}, 城市: {row['city']}")JavaScript 文件操作
基本文件操作(Node.js)
javascript
// JavaScript - 文件操作(Node.js)
import { promises as fs } from "fs";
// 写入文件
async function writeFile() {
try {
await fs.writeFile(
"example.txt",
"Hello, World!\n这是第二行\nJavaScript 文件操作示例\n",
"utf-8"
);
console.log("文件写入成功");
} catch (error) {
console.error("写入文件失败:", error);
}
}
// 追加内容
async function appendFile() {
try {
await fs.appendFile("example.txt", "这是追加的内容\n", "utf-8");
console.log("内容追加成功");
} catch (error) {
console.error("追加内容失败:", error);
}
}
// 读取文件
async function readFile() {
try {
const content = await fs.readFile("example.txt", "utf-8");
console.log("整个文件内容:");
console.log(content);
// 逐行读取
const lines = content.split("\n");
console.log("逐行读取:");
lines.forEach((line, index) => {
if (line.trim()) {
console.log(`第${index + 1}行: ${line}`);
}
});
} catch (error) {
console.error("读取文件失败:", error);
}
}
// 执行文件操作
async function main() {
await writeFile();
await appendFile();
await readFile();
}
main();二进制文件操作
javascript
// JavaScript - 二进制文件操作
import { promises as fs } from "fs";
// 写入二进制文件
async function writeBinaryFile() {
try {
const data = Buffer.from("Hello, Binary World!", "utf-8");
await fs.writeFile("example.bin", data);
console.log("二进制文件写入成功");
} catch (error) {
console.error("写入二进制文件失败:", error);
}
}
// 读取二进制文件
async function readBinaryFile() {
try {
const binaryData = await fs.readFile("example.bin");
console.log(`二进制数据: ${binaryData}`);
console.log(`转换为字符串: ${binaryData.toString("utf-8")}`);
} catch (error) {
console.error("读取二进制文件失败:", error);
}
}
// 复制文件
async function copyFile(source, destination) {
try {
const data = await fs.readFile(source);
await fs.writeFile(destination, data);
console.log("文件复制成功");
} catch (error) {
console.error("文件复制失败:", error);
}
}
// 执行二进制文件操作
async function binaryMain() {
await writeBinaryFile();
await readBinaryFile();
await copyFile("example.txt", "example_copy.txt");
}
binaryMain();JSON 文件操作
javascript
// JavaScript - JSON 文件操作
import { promises as fs } from "fs";
// 写入 JSON 文件
async function writeJsonFile() {
const data = {
name: "Alice",
age: 25,
city: "New York",
hobbies: ["reading", "coding", "traveling"],
isStudent: true,
};
try {
await fs.writeFile("data.json", JSON.stringify(data, null, 2), "utf-8");
console.log("JSON 文件写入成功");
} catch (error) {
console.error("写入 JSON 文件失败:", error);
}
}
// 读取 JSON 文件
async function readJsonFile() {
try {
const content = await fs.readFile("data.json", "utf-8");
const loadedData = JSON.parse(content);
console.log("JSON 数据:");
console.log(JSON.stringify(loadedData, null, 2));
} catch (error) {
console.error("读取 JSON 文件失败:", error);
}
}
// 追加 JSON 数据
async function appendJsonData(filename, newData) {
try {
let existingData;
try {
const content = await fs.readFile(filename, "utf-8");
existingData = JSON.parse(content);
} catch (error) {
if (error.code === "ENOENT") {
existingData = [];
} else {
throw error;
}
}
if (Array.isArray(existingData)) {
existingData.push(newData);
} else {
existingData = [existingData, newData];
}
await fs.writeFile(
filename,
JSON.stringify(existingData, null, 2),
"utf-8"
);
console.log("JSON 数据追加成功");
} catch (error) {
console.error("追加 JSON 数据失败:", error);
}
}
// 执行 JSON 文件操作
async function jsonMain() {
await writeJsonFile();
await readJsonFile();
await appendJsonData("data.json", { name: "Bob", age: 30 });
}
jsonMain();CSV 文件操作
javascript
// JavaScript - CSV 文件操作
import { promises as fs } from "fs";
// 写入 CSV 文件
async function writeCsvFile() {
const data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"],
["Charlie", 35, "Chicago"],
];
const csvContent = data.map((row) => row.join(",")).join("\n");
try {
await fs.writeFile("people.csv", csvContent, "utf-8");
console.log("CSV 文件写入成功");
} catch (error) {
console.error("写入 CSV 文件失败:", error);
}
}
// 读取 CSV 文件
async function readCsvFile() {
try {
const content = await fs.readFile("people.csv", "utf-8");
const lines = content.split("\n");
console.log("CSV 数据:");
lines.forEach((line, index) => {
if (line.trim()) {
console.log(`行 ${index + 1}: ${line}`);
}
});
} catch (error) {
console.error("读取 CSV 文件失败:", error);
}
}
// 使用字典读写 CSV
async function writeDictCsv() {
const peopleData = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "Los Angeles" },
{ name: "Charlie", age: 35, city: "Chicago" },
];
const headers = ["name", "age", "city"];
const csvContent = [
headers.join(","),
...peopleData.map((person) =>
headers.map((header) => person[header]).join(",")
),
].join("\n");
try {
await fs.writeFile("people_dict.csv", csvContent, "utf-8");
console.log("字典 CSV 文件写入成功");
} catch (error) {
console.error("写入字典 CSV 文件失败:", error);
}
}
// 执行 CSV 文件操作
async function csvMain() {
await writeCsvFile();
await readCsvFile();
await writeDictCsv();
}
csvMain();文件操作对比
| 操作 | Python | JavaScript (Node.js) |
|---|---|---|
| 写入文件 | open('file.txt', 'w') | fs.writeFile() |
| 读取文件 | open('file.txt', 'r') | fs.readFile() |
| 追加文件 | open('file.txt', 'a') | fs.appendFile() |
| 二进制操作 | open('file.bin', 'wb') | fs.writeFile() + Buffer |
| 错误处理 | try/except | try/catch |
| 编码指定 | encoding='utf-8' | 第二个参数 |
高级文件操作
Python 高级操作
python
# Python - 文件系统操作
import os
import shutil
# 检查文件是否存在
if os.path.exists('example.txt'):
print("文件存在")
# 获取文件信息
file_stat = os.stat('example.txt')
print(f"文件大小: {file_stat.st_size} 字节")
print(f"修改时间: {file_stat.st_mtime}")
# 列出目录内容
files = os.listdir('.')
print("当前目录文件:")
for file in files:
if os.path.isfile(file):
print(f"文件: {file}")
elif os.path.isdir(file):
print(f"目录: {file}")
# 创建目录
os.makedirs('new_directory', exist_ok=True)
# 移动文件
shutil.move('example.txt', 'new_directory/example.txt')
# 删除文件
os.remove('example_copy.txt')JavaScript 高级操作
javascript
// JavaScript - 文件系统操作
import { promises as fs } from "fs";
import { promises as path } from "path";
// 检查文件是否存在
async function checkFileExists() {
try {
await fs.access("example.txt");
console.log("文件存在");
} catch (error) {
console.log("文件不存在");
}
}
// 获取文件信息
async function getFileInfo() {
try {
const stats = await fs.stat("example.txt");
console.log(`文件大小: ${stats.size} 字节`);
console.log(`修改时间: ${stats.mtime}`);
} catch (error) {
console.error("获取文件信息失败:", error);
}
}
// 列出目录内容
async function listDirectory() {
try {
const files = await fs.readdir(".");
console.log("当前目录文件:");
for (const file of files) {
const stats = await fs.stat(file);
if (stats.isFile()) {
console.log(`文件: ${file}`);
} else if (stats.isDirectory()) {
console.log(`目录: ${file}`);
}
}
} catch (error) {
console.error("列出目录失败:", error);
}
}
// 执行高级文件操作
async function advancedMain() {
await checkFileExists();
await getFileInfo();
await listDirectory();
}
advancedMain();练习
- 创建一个程序,读取文本文件并统计单词数量
参考答案:
python
# Python
with open('example.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = text.split()
print('单词数量:', len(words))javascript
// JavaScript (Node.js)
const fs = require("fs");
fs.readFile("example.txt", "utf-8", (err, data) => {
if (err) throw err;
const words = data.split(/\s+/);
console.log("单词数量:", words.length);
});- 实现一个简单的日志系统,将日志写入文件
参考答案:
python
# Python
def log(msg):
with open('log.txt', 'a', encoding='utf-8') as f:
f.write(msg + '\n')
log('程序启动')javascript
// JavaScript (Node.js)
const fs = require("fs");
function log(msg) {
fs.appendFileSync("log.txt", msg + "\n", "utf-8");
}
log("程序启动");- 创建一个配置文件读写工具,支持 JSON 格式
参考答案:
python
# Python
import json
def save_config(data, filename):
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def load_config(filename):
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
save_config({'a': 1}, 'config.json')
print(load_config('config.json'))javascript
// JavaScript (Node.js)
const fs = require("fs");
function saveConfig(data, filename) {
fs.writeFileSync(filename, JSON.stringify(data, null, 2), "utf-8");
}
function loadConfig(filename) {
return JSON.parse(fs.readFileSync(filename, "utf-8"));
}
saveConfig({ a: 1 }, "config.json");
console.log(loadConfig("config.json"));- 实现文件备份功能,自动复制重要文件
参考答案:
python
# Python
import shutil
shutil.copy('important.txt', 'important_backup.txt')javascript
// JavaScript (Node.js)
const fs = require("fs");
fs.copyFileSync("important.txt", "important_backup.txt");- 比较 Python 和 JavaScript 的文件操作差异
参考答案:
- Python 文件操作更简洁,内置 open/read/write,支持 with 语法自动关闭。
- JavaScript (Node.js) 需引入 fs 模块,异步为主,API 更丰富,适合大规模 IO。
下一步
现在你已经了解了文件操作,接下来我们将学习 Python 的内置模块。