deleting the last row of csv file
12 views (last 30 days)
Show older comments
Hello. I have a large csv file with header information. I simply wish to delte the last row,replacing it as blanks and resave the file with the same name. I would have thought this was easy but have had a devil of a time doing this. Ideally, I would like a method to work on both Mac and PC platforms, so not sure how well suited xlswrite is (or if that previously nonfunctionality on Macs is no longer an issue)—but would want ultimately to merely go to that last row and delte it. I would need to keep everything else in the the same, including the header info and .csv format. Thank you in advance.
0 Comments
Accepted Answer
dpb
on 4 Sep 2022
Edited: dpb
on 4 Sep 2022
If have R2020b or later, the simplest portable coding solution would be
data=readlines('yourfile.csv');
data(end)="";
writematrix(data,'yourfile.csv')
Try as above, you may want/need the 'QuoteStrings',0 name-value pair argument; it is supposed to be off by default for text files, but I've found that isn't always true; it does quote strings on its own volition. I've not yet been able to discern the condition(s) under which that occurs enough to be able to predict when it will/will not produce the unexpected result so end up either setting it to be sure or by just waiting to see what it does and then fix it if needs must...
5 Comments
dpb
on 6 Sep 2022
Edited: dpb
on 6 Sep 2022
fn='https://www.mathworks.com/matlabcentral/answers/uploaded_files/1117700/CSV_example.csv';
data=readlines(fn);
data(end)=[];
writematrix(data,'newfile.csv')
type('newfile.csv')
OK, this is one of the cases where the default 'QuoteStrings' name-value pair that is supposed to be 'false' by default isn't -- I mentioned you might find this out in the original Answer. You can force it by using
writematrix(data,'newfile.csv','QuoteStrings',false)
type('newfile.csv')
If your're computing a row to delete logically, can use the index into the array as logical indexing expression or actual line number(s) to delete besides just end as the subscripting expression.
Remember, however, if you delete multiple rows that must either do so in one subscripting expression or from last to least. If otherwise, deleting a row prior to another that is to be removed will change the indexing into all those following the first.
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!