# Appending to a .csv file [duplicate]

I have a selection of Lists of data which are in the same format, and if I Export them all to CSV at the same time I get a nice result which I can then Import again to get back the data in the same formats. I also need to be able to append to a previously written file. I have tried a selection of ways of doing this and I cannot get a sensible result. Can somebody show me how?

With data in my row format, which is a List of Lists with a specific definition, and f = OpenAppend[filename <> ".csv"], I have tried things like;

Write[f, data];


and

Write[f, #]&@@data;


and

Write[f, #]&/@data;


and

(Write[f, #];WriteString[f,","])&/@data;


none of which work.

Solution by J. M. needs help;

WriteString[str, "\n"<>ExportString[{{4, d, "D"}}, "CSV"]]


data = {{1, a, "A"}, {2, b, "B"}, {3, c, "C"}};
Export["data.csv", data];

str = OpenAppend["data.csv"];
WriteString[str, "4,\"d\",\"D\"\n"]
Close[str];

FilePrint["data.csv"]

1,"a","A"
2,"b","B"
3,"c","C"
4,"d","D"


You can use a formatting function, e.g.

data2 = {{5, e, "E"}, {6, f, "F"}};

format[{x_, y_, z_}] := StringJoin[
ToString[x], ",\"", ToString[y], "\",\"", z, "\"\n"]

str = OpenAppend["data.csv"];
WriteString[str, format[#]] & /@ data2;
Close[str];

FilePrint["data.csv"]

1,"a","A"
2,"b","B"
3,"c","C"
4,"d","D"
5,"e","E"
6,"f","F"

• You could do WriteString[str, ExportString[{{4, d, "D"}}, "CSV"]] as well. Mar 28 '18 at 13:42
• Thanks for your solutions! I think J.M.'s solution is what I was after. It just needs a newline character
– Joe
Mar 29 '18 at 10:09