檔案讀寫
學習檔案讀寫,掌握 JSON 與 CSV 資料格式。讓程式能與外部檔案互動,處理真實世界的資料。
1 什麼是檔案讀寫?
在資料科學與程式開發中,常需要 讀取檔案資料 或 將資料寫入檔案,以便儲存、分析或交換資訊。
Node.js 提供 fs(File System)模組,可以方便操作檔案。
2 fs 模組基礎
2.1 匯入 fs 模組
import fs from 'fs';
如果你使用 Node.js 並且在
package.json
中設置"type": "module"
,即可使用 ES6 模組方式匯入。
2.2 讀取檔案(同步方式)
let content = fs.readFileSync('example.txt', 'utf-8');
console.log(content);
readFileSync
:同步讀取檔案- 第二個參數
'utf-8'
指定編碼
2.3 寫入檔案(同步方式)
let data = "Hello, Data Science!";
fs.writeFileSync('output.txt', data, 'utf-8');
console.log("寫入完成!");
writeFileSync
:同步寫入檔案- 若檔案不存在,會自動建立
2.4 小練習
- 建立一個
example.txt
,寫入任意文字 - 使用程式讀取
example.txt
,並印出內容 - 將讀到的內容再寫入
copy.txt
3 JSON 檔案操作
JSON 是資料交換常用格式,Node.js 可方便處理。
3.1 讀取 JSON 檔案
假設有 data.json
:
{
"name": "Alice",
"age": 20,
"scores": [90, 85, 78]
}
程式讀取方式:
let raw = fs.readFileSync('data.json', 'utf-8');
let obj = JSON.parse(raw);
console.log(obj.name); // Alice
console.log(obj.scores); // [90, 85, 78]
3.2 寫入 JSON 檔案
let student = {
name: "Bob",
age: 21,
scores: [88, 92, 79]
};
let jsonStr = JSON.stringify(student, null, 2); // 格式化
fs.writeFileSync('student.json', jsonStr, 'utf-8');
console.log("JSON 寫入完成!");
JSON.stringify(obj, null, 2)
可以美化格式,方便閱讀
3.3 小練習
- 建立一個學生物件,包含姓名、年齡與成績
- 將物件寫入
student.json
- 再讀取
student.json
,印出姓名與平均分
4 CSV 檔案操作
CSV 是另一種常見資料格式,純文字以逗號分隔值(Comma-Separated Values)。
4.1 讀取 CSV 檔案(簡單方式)
假設 scores.csv
內容:
name,math,english,science
Alice,90,85,78
Bob,88,92,79
程式讀取:
let raw = fs.readFileSync('scores.csv', 'utf-8');
let lines = raw.split('\n');
for (let line of lines) {
let cols = line.split(',');
console.log(cols);
}
split('\n')
將每行分割split(',')
將每列分割成欄位
5 CSV 進階操作
5.1 讀取 CSV 並計算平均分
假設 scores.csv
內容如下:
name,math,english,science
Alice,90,85,78
Bob,88,92,79
Charlie,75,80,85
程式範例:
import fs from 'node:fs';
let raw = fs.readFileSync('scores.csv', 'utf-8');
let lines = raw.split('\n');
// 移除標題列
let headers = lines.shift().split(',');
for (let line of lines) {
let cols = line.split(',');
let name = cols[0];
let scores = cols.slice(1).map(Number); // 轉成數字
let sum = scores.reduce((a, b) => a + b, 0);
let avg = sum / scores.length;
console.log(`${name} 的平均分數: ${avg.toFixed(2)}`);
}
.map(Number)
:將字串轉成數字.reduce((a,b)=>a+b,0)
:計算總和- 計算平均分數並印出
5.2 小練習
建立至少 3 位學生的 CSV 檔案
計算每位學生的總分與平均分數
印出結果,格式如下:
Alice: 總分 253, 平均 84.33
5.3 寫入計算結果至 CSV
將計算結果寫入新的檔案 averages.csv
:
let results = lines.map(line => {
let cols = line.split(',');
let name = cols[0];
let scores = cols.slice(1).map(Number);
let avg = scores.reduce((a, b) => a + b, 0) / scores.length;
return `${name},${avg.toFixed(2)}`;
}).join('\n');
fs.writeFileSync('averages.csv', results, 'utf-8');
console.log("平均分數已寫入 averages.csv");
5.4 JSON 與 CSV 轉換
將 CSV 轉成 JSON:
let jsonData = lines.map(line => {
let cols = line.split(',');
return {
name: cols[0],
math: Number(cols[1]),
english: Number(cols[2]),
science: Number(cols[3])
};
});
fs.writeFileSync('scores.json', JSON.stringify(jsonData, null, 2), 'utf-8');
console.log("已將 CSV 轉成 JSON!");
5.5 小練習
- 讀取
scores.csv
- 計算每位學生平均分
- 將結果寫入新的 CSV
- 將原始資料轉成 JSON 格式,寫入檔案