MATLAB Answers

Issue importing a sequence of numbered files with fopen

2 views (last 30 days)
Matthew Rogers
Matthew Rogers on 16 Jun 2021
Commented: Matthew Rogers on 16 Jun 2021
I'm trying to import a sequence of numbered csv files with headers (Test_1.csv, Test_2.csv etc.) using fopen and concatenate them vertically, writing them to a single file with only the headers from the first file (since they are all the same). However I keep getting the error "Error using fread, invalid file identifier. Use fopen to generate a valid file identifier". I know that means that fopen has likely failed to open the file, but I cannot see what the problem is. The script is heavily based on another I found which originally opened a dialog box using uigetfile to browse for input files, but I just want it to read numbered files in sequence. Please help!
%Number of rows of headers in each file
NumHeaders = 1;
%path name
pname = 'C:\Users\mbgnrmr4\Dropbox (Research Group)\Coding stuff\MATLAB\Miscellaneous function tests\';
% Create output file name in the same folder.
outputFileName = fullfile(pname, 'finalCSVnew.csv')
fidOutput = fopen(outputFileName, 'wt');% open output file to write
V = 1:3 %File numbers that need to be imported
N = numel(V)
fidInput = cell(1,N)
filenames = cell(1,N)
for k = 1 : N
% Input file name.
filenames{k} = sprintf('Test_%01d.cpr', V(k))
thisFileName = fullfile(pname, filenames{k})
% Open input file:
fidInput{k} = fopen(thisFileName, 'rt');
%skip headers except for first file
if k ~= 1
for L = 1 : NumHeaders; fgetl(fidInput{k}); end
% Read text from it
thisText = fread(fidInput{k}, '*char');
% Copy to output file:
fwrite(fidOutput, thisText);
fclose(fidInput{k}); % close the input file
fido=fclose(fidOutput); clear fid*
% Open Windows Explorer to this folder
Matthew Rogers
Matthew Rogers on 16 Jun 2021
It did not exist! I used the wrong file extension, I put .cpr instead of .csv! Thanks!

Sign in to comment.

Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by