Question

I want to acces a .csv file, look for empty data blocks and store all of the lines that have no empty data blocks.

This is my code:

   filename = 'C:\Users\try.csv'; 
   file1 = fopen(filename);     %Acces file with empty data blocks
   filename2 = 'C:\Users\try_corrected.csv';
   file2 = fopen(filename2);    %Acces destination file

   tline = fgets(file1);        %Read the first line of file1

   while ischar(tline)

       detected = false;
       [r,s] = size(tline);     %Determine the lengt of the textline for the for-loop

       for(i=1: 1: s)
           if( (tline(i)==',' && tline(i+1) ==',') || tline(1)==',' || tline(s-2)==',' )

              detected = true   %Line should not be printed in destination file
              break;

           end
       end

       if detected == false
          fprintf(file2,'%s\n',tline);
       end

       tline = fgets(file1);

  end

  type 'C:\Users\try_corrected.csv'
  fclose(file2);

  textdata = textscan(file1, '%s %f %f %f %s %f %f %f %s %f %s','HeaderLines', 1,'Delimiter',',');
  fclose(file1);

If I do the "type" command, I should see all the printed strings which is not the case. Am I using fprintf wrong? I know there is a command called csvwrite but I thought this could work too?

Was it helpful?

Solution

First, when you open your destination file you need to open it for writing. Without a second parameter fopen will open for read access. If your destination file did not exist it would return you a -1 file handle.

Use instead:

fopen(filename2,'w')

Here is a simplified version of your code including that amendment:

filename = 'c:\try.csv'; 
fid_in = fopen(filename,'r');     %Access file with empty data blocks
filename2 = 'C:\try_corrected.csv';
fid_out = fopen(filename2,'w');    %Access destination file

while (~feof(fid_in))
    str=fgets(fid_in);
    if (~doublecommas(str))
        fprintf(fid_out,'%s',str);
    end    
end

fclose(fid_in);
fclose(fid_out);

type(filename2)

This uses a different method to detect double presence of commas in the CSV line:

function flag=doublecommas(str)

    flag=false; % flag = result returned, 
                %        true if empty CSV fields present in line

    if (ischar(str) && length(str)>0)

        for cindex=1:length(str)-1
            if strcmp(str(cindex:(cindex+1)),',,')
                flag=true; break;
            end
        end

    end

return;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top