I just need help exporting array elements to a csv file. I don't know what's wrong with my code. Any help is gladly appreciated. Thanks.
for (int index = 0; index < cols.length; index++)
{
FileWriter fw = new FileWriter(newFileName);
if (index == cols.length - 1)
{
fw.append(cols[index]);
}
else
{
fw.append(cols[index]);
fw.append(",");
}
}
When I run this. Nothing happens to my csv file. Infact, it wipes everything of. Please help.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.
Click File > Import. In the Import window, click Team > Work Items from CSV. Click Next. Click Browse and select the CSV file to import.
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java.
Assuming you're storing String in your array, I post an alternative solution:
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
// Append strings from array
for (String element : array) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString());
br.close();
Best regards.
you need to flush the written data, close your FileWriter.
finally {
fw.close(); // close will automatically flush the data
}
Also, use BufferedWriter or PrintWriter instead as they are highly efficient and evolved than FileWriter.
Btw, declare the FileWriter outta your for loop. Currently it will overwrite the column for each iteration.
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