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

조회 수: 14 (최근 30일)
Michael Basford
Michael Basford 2020년 2월 21일
답변: Image Analyst 2020년 2월 22일
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

답변 (1개)

Image Analyst
Image Analyst 2020년 2월 22일
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.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by