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

16 ビュー (過去 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 Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by