Reading files and writing with new extension

조회 수: 3 (최근 30일)
jhz
jhz 2020년 2월 6일
편집: jhz 2020년 2월 6일
I am trying to read a bunch of images in a directory and after some processing I want to use image file's names to write and save a new file same as the image file names. I am close but having issue to get rid of image file extension in the new file names. When I save new file (a .txt file) using the image file name, I also get image extension. I am pasting below the code I am using, please help me to figure this out.
This code gives me output in the form, e.g; img1.jpg.txt. What I want is img1.txt.
%Specify the folder where the file live
myFolder='C:\Users\UserName\Desktop\test';
cd(myFolder);
%Check to make sure the folder actually exists
if ~isfolder(myFolder)
errorMessage=sprintf('Error: the following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% get the list of all files in the folder with desired file pattern/type.
filePattern=fullfile(myFolder, '*.jpg');
theFiles=dir(filePattern);
jpgFiles = cell(1, numel(theFiles));
for k=1:length(theFiles)
baseFileName=theFiles(k).name;
jpgFiles{k} = baseFileName;
end
A = [1 2 3; 4 5 6; 7 8 9];
for i=1:numel(theFiles)
txtFileName = fullfile(myFolder, sprintf([jpgFiles{i},'.txt']));
txtFileID = fopen(txtFileName, 'w');
fprintf(txtFileID, 'myHeader 1, myHeader 2 \n');
fprintf(txtFileID, '%d \n', A);
fclose(txtFileID);
end
  댓글 수: 2
Stephen23
Stephen23 2020년 2월 6일
You mixed up two different approaches to adding a file extension to the name, which are:
  1. [jpgFiles{i},'.txt']
  2. sprintf('%s.txt',jpgFiles{i})
Your code concatenates first and then inputs the complete filename as the format string to sprintf, which is not only completely superfluous but can change any special characters in the format string or throw errors for escaped characters that are not valid. Pick one of the above methods, but do NOT mix them together!
jhz
jhz 2020년 2월 6일
I got it and thank you so much for the quick response.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2020년 2월 6일
편집: Stephen23 2020년 2월 6일
Use fileparts, something like this:
[~,fnm] = fileparts(jpgFiles{i});
fullfile(myFolder, sprintf('%s.txt',fnm))
  댓글 수: 1
jhz
jhz 2020년 2월 6일
편집: jhz 2020년 2월 6일
Thank you so much, it worked!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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