How to change extension of selected file extensions in a directory?

35 views (last 30 days)
Hi, I'm looking to change all the .s2p file extensions in my working directory into .txt. However, I'm having a hard time doing this. I though I'd be able to use
[filelocation, name, ext] = fileparts(files(id))
But matlab tells me the input must be a row of vectors of characters or string vector - I am not understanding exactly how this functions.
Here's my code as it stands - where should I be going next?
% Converts all given file extensions in a directory
convertfrom = '.s2p';
convertto = '.txt';
% Gets all files of type in current dir
filesnames = "*." + convertfrom;
files = dir(filesnames);
% Loops through each
for id = 1:length(files)
% Get the file name, ext etc
[filelocation, name, ext] = fileparts(files(id))
end

Answers (1)

Image Analyst
Image Analyst on 22 Feb 2020
Try this:
% Specify the folder where the files live.
myFolder = pwd; % or 'C:\Users\yourUserName\Documents\My SP2 files'; or whatever.
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Specify the old/current extension.
oldExtension = '.sp2';
% Specify the desired extension
desiredExtension = '.txt';
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, sprintf('*%s', oldExtension)) % Change to whatever pattern you need, like '*.sp2'
% Get a file listing of files in myFolder from the operating system:
theFiles = dir(filePattern);
% Now loop over all found files, renaming each in turn with the new desired extension:
for k = 1 : length(theFiles)
% Get the input filename.
baseFileName = theFiles(k).name;
fullInputFileName = fullfile(myFolder, baseFileName);
% Get the output filename
fullOutputFileName = strrep(fullInputFileName, oldExtension, desiredExtension);
fprintf(1, 'Now renaming %s\n to %s\n', fullInputFileName, fullOutputFileName);
% Now do the actual renaming:
movefile(fullInputFileName, fullOutputFileName);
end
code adapted from the FAQ. Adapt further as needed.

Categories

Find more on Startup and Shutdown 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!