I want to add new row in exist csv file? if csv file exist, then i don't want to add column header and just want to add new row after exist row in the file.
Here is code which I'm trying:
var fields = ['total', 'results[0].name.val'];
var fieldNames = ['Total', 'Name'];
var opts1 = {
data: data,
fields: fields,
fieldNames: fieldNames,
newLine: '\r\n'
};
var opts2 = {
newLine: '\r\n',
data: data,
fields: fields,
fieldNames: fieldNames,
hasCSVColumnTitle: false,
};
fs.stat('file.csv', function (err, stat) {
if (err == null) {
console.log('File exists');
var csv = json2csv(opts2);
fs.appendFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
} else if (err.code == 'ENOENT') {
// file does not exist
var csv = json2csv(opts1);
fs.writeFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('file saved');
});
} else {
console.log('Some other error: ', err.code);
}
});
Appending dataframe means adding data rows to already existing files. To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function.
The corresponding example below writes to a CSV file using the writeFile function of the fs module: const fs = require("fs"); const data = ` id,name,age 1,Johny,45 2,Mary,20 `; fs. writeFile("data. csv", data, "utf-8", (err) => { if (err) console.
A CSV is a plain text file format for storing tabular data. The CSV file uses a comma delimiter to separate values in table cells, and a new line delineates where rows begin and end.
The following code will do what you asked:
var fs = require('fs');
var json2csv = require('json2csv');
var newLine = '\r\n';
var fields = ['Total', 'Name'];
var appendThis = [
{
Total: '100',
Name: 'myName1',
},
{
Total: '200',
Name: 'myName2',
},
];
var toCsv = {
data: appendThis,
fields: fields,
header: false,
};
fs.stat('file.csv', function (err, stat) {
if (err == null) {
console.log('File exists');
//write the actual data and end with newline
var csv = json2csv(toCsv) + newLine;
fs.appendFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
} else {
//write the headers and newline
console.log('New file, just writing headers');
fields = fields + newLine;
fs.writeFile('file.csv', fields, function (err) {
if (err) throw err;
console.log('file saved');
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With