如何在Node.js中移除CSV文件多余逗号且不偏移数据?
解决CSV单个逗号单元格置空且不偏移的问题
需求
要把CSV文件中内容仅为单个逗号的单元格置为空,同时必须保持原有列结构,不能让数据发生偏移。
输入表格
| a | b | c | d | e | f |
|---|---|---|---|---|---|
| First row | 1 | 0 | , | , | , |
| Second row | 1 | 1 | 3 | , | , |
| Third row | 1 | , | 3 | , | , |
期望输出表格
| a | b | c | d | e | f |
|---|---|---|---|---|---|
| First row | 1 | 0 | |||
| Second row | 1 | 1 | 3 | ||
| Third row | 1 | 3 |
原代码问题
你写的代码逻辑有误:它试图合并连续的逗号(遇到连续逗号时跳过一个),这会直接减少CSV的列数,导致后面的数据往前偏移,不符合需求。
修正后的代码
下面的代码会按单元格拆分内容,只把内容为单个逗号的单元格替换为空,同时保留所有分隔逗号,确保列结构不变:
const fs = require('fs'); const readline = require('readline'); // 将内容为单个逗号的单元格置空,保留CSV列结构 function replaceCommaCells(line) { let withinQuotes = false; let currentCell = ''; const cells = []; for (let i = 0; i < line.length; i++) { const char = line[i]; // 处理带引号的单元格(内部逗号不视为分隔符) if (char === '"') { withinQuotes = !withinQuotes; currentCell += char; } else if (char === ',' && !withinQuotes) { // 遇到分隔逗号,处理当前单元格 cells.push(currentCell.trim() === ',' ? '' : currentCell); currentCell = ''; } else { currentCell += char; } } // 处理最后一个单元格 cells.push(currentCell.trim() === ',' ? '' : currentCell); // 重新拼接成CSV行,保证列数不变 return cells.join(','); } // 处理CSV文件 function processCSVFile(filePath) { const outputFilePath = '../70_primary_codesData2CSV/70 Primary Codes Data/19120/19120(828+828_new)withoutExtraS.csv'; const fileStream = fs.createReadStream(filePath); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); const outputStream = fs.createWriteStream(outputFilePath); rl.on('line', (line) => { const processedLine = replaceCommaCells(line); outputStream.write(processedLine + '\n'); }); rl.on('close', () => { console.log('CSV文件处理完成。'); }); } // 使用示例 const filePath = '../70_primary_codesData2CSV/70 Primary Codes Data/19120/19120(828+828_new).csv'; // 替换为你的输入文件路径 processCSVFile(filePath);
关键逻辑说明
- 按单元格拆分:遍历每行内容,把每个单元格的内容单独收集,遇到分隔逗号时结束当前单元格的收集。
- 单个逗号判断:对每个收集到的单元格,判断是否仅为单个逗号(
trim()是避免单元格前后有空格的情况),是则替换为空字符串。 - 保留引号内内容:处理带引号的单元格时,内部的逗号不会被视为分隔符,确保类似
"test,content"的单元格不会被误修改。 - 重新拼接列:处理完所有单元格后,用逗号重新拼接,保证列数和原文件完全一致,不会出现数据偏移。
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

