MATLAB: Removing the top rows of a csv file

csvfolder

I have a folder with multiple .csv files, similar to the one attached here. I am trying to remove the top rows of this csv file (everything until the row with Time and Trace). I need a script to run through the folder, delete all the top row portion of the files and resave them. Could you please help me with that? Thank you.

Best Answer

Folder = 'D:\Your\Folder';
FileList = dir(fullfile(Folder, '*.csv'));
for iFile = 1:numel(FileList)
File = fullfile(Folder, FileList(iFile).name);
% Read the file:
FID = fopen(File, 'r');
if FID < 0
error('Cannot open file: %s', File);
end
C = fread(FID, [1, inf], '*char'); % [EDITED] inf -> [1, inf]
fclose(FID);
index = strfind(C, 'Time (s)');
if numel(index) ~= 1
error('Key not found in file: %s', File);
end
% Write cropped contents:
FID = fopen(File, 'w');
if FID < 0
error('Cannot open file: %s', File);
end
fwrite(FID, C(index:numel(C)), '*char');
fclose(FID);
end
Create a backup at first or write to a new folder:
InFolder = 'D:\Your\Folder';
FileList = dir(fullfile(InFolder, '*.csv'));
OutFolder = 'D:\Your\FolderModified';
mkdir(OutFolder);
for iFile = 1:numel(FileList)
InFile = fullfile(InFolder, FileList(iFile).name);
...
OutFile = fullfile(OutFolder, FileList(iFile).name);
...
end