gpt4 book ai didi

javascript - 删除一行 csv 或忽略它

转载 作者:数据小太阳 更新时间:2023-10-29 05:31:16 25 4
gpt4 key购买 nike

我正在使用 fast-csv 读取 csv 文件,但我的文件格式与 fast-csv 的预期格式不完全相同:

First line with some details (not important)
Second line with header
Third line with data
Fourth line with data
...

以及我是如何阅读它的:

const csv = require('fast-csv');
const stream = fs.createReadStream('myfile.csv');
const csvStream = csv
.fromStream(stream,
{
headers: true,
delimiter: ',',
rowDelimiter: '\n',
quoteHeaders: false,
quoteColumns: false
})
.on("data", data => {
// i do something with datas

})
.on("error", error => {
console.log("CSV is invalid !", error);
})
.on("end", data => {
console.log("End of parsing");
console.log(data);
});

这里的问题是

headers: true,

将查找第一行作为标题,这就是我要删除第一行或忽略它的原因。怎么做 ? (我知道我可以在没有第一行的情况下读取文件和写入文件,但我认为这不是正确的方法...)

版本: Node v10.0.0 & fast-csv 5.6.0


编辑:使用@Anders Carstensen 示例进行测试:

const file = 'myfile.csv';
const fs = require("fs");
const stream = fs.createReadStream(file, {
encoding: 'utf8'
});

stream.on('readable', () => {
// Read through the stream until we encounter a new line
let chunk;
while (null !== (chunk = stream.read(1))) {

if (chunk == '\n'){
console.log('line break');
break;
}
}
console.log('test');


// CSV parsing
const csvStream = csv.fromStream(stream,
{
renameHeaders: false,
headers: true,
delimiter: ',',
rowDelimiter: '\n',
quoteHeaders: false,
quoteColumns: false
})
.on("data", data => {
console.log(data);

})
.on("error", error => {
console.log("CSV invalid !", error);
})
.on("end", data => {
console.log("End of parsing");
console.log(data);
});
});

输出:

line break
test
line break
test

Edit2:检查@Anders Carstensen 的答案以获取解决方案(问题是使用 .on 而不是 .once)

最佳答案

首先,您应该仔细检查不希望解析器查看的流部分。我一直读到这里,直到遇到第一个新行 (\n)。

var fs = require('fs'),
csv = require('fast-csv');

var stream = fs.createReadStream('c:\\temp\\test.csv', {
encoding: 'utf8'
});

stream.once('readable', function () {
// Read through the stream until we encounter a new line
var chunk;
while (null !== (chunk = stream.read(1))) {
if (chunk === '\n')
break;
}

// Then do the CSV parsing
const csvStream = csv
.fromStream(stream,
{
headers: true,
delimiter: ',',
rowDelimiter: '\n',
quoteHeaders: false,
quoteColumns: false
})
.on("data", data => {
// i do something with datas
console.log('data', data);
})
.on("data-invalid", data => {
console.log('invalid data', data);
})
.on("error", error => {
console.log("Le fichier CSV est invalide !", error);
})
.on("end", data => {
console.log("End of parsing");
console.log(data);
});
});

关于javascript - 删除一行 csv 或忽略它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51475256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com