Error when writing file names into a txt file ("nonscalar strings are unsupported")
Ältere Kommentare anzeigen
I have a number of pictures in a folder and I would like to simply get their file names and write them into a txt file:
% input: pictures contained in "myfolder"
% 0013_DSC8315.jpg
% 0020_SOF8150.jpg
% 0068_DSC8440.jpg
% 0077_SOF8212.jpg
% 0089_DSC8481.jpg
% my attempt
a = dir('/.../myfolder');
b = {a(3:end).name}';
b = string(strrep(b, '.jpg', ''))
fid =fopen('/.../pics_names.txt', 'w' );
fwrite(fid, b);
fclose(fid);
However, I get the following output and error message
b =
5×1 string array
"0013_DSC8315"
"0020_SOF8150"
"0068_DSC8440"
"0077_SOF8212"
"0089_DSC8481"
Error using fwrite
Cannot write value: nonscalar strings are unsupported.
Error in untitled (line 5)
fwrite(fid, b);
How to solve this error? :-)
3 Kommentare
Stephen23
am 14 Jan. 2024
b = {a(3:end).name}';
https://www.mathworks.com/matlabcentral/answers/1699230-folder-listing-with-dir-on-mac#answer_945260
As Walter Roberson wrote: "That code is wrong on every operating system that MATLAB has ever run on".
The recommended approach is to specify a non-empty DIR search name, or use e.g. ISMEMBER, SETDIFF, or similar:
In addition to what Stephen has mentioned, since you know that the extension of all the files is same and you want to read all the files with the same given extension, why not search accordingly?
Here's a simplfied version of what you want to do -
%Generating and saving some plots for example
for k=1:5
plot(rand(1,10))
ax = gca;
exportgraphics(ax,"Plot_" + randi(1000) + ".jpg")
end
%Check the contest of the current folder
ls
%Search and get files with .jpg extension
jpgFiles = dir('*.jpg');
%Extract the names
names = {jpgFiles.name}
%Get the names without the extension
y = extractBefore(names, '.jpg').'
%Write to a text file via writecell() - Assuming you are working with R2019a
%or a later version
writecell(y, 'pics_names.txt')
%Display the contents of the saved text file
type pics_names.txt
Sim
am 16 Jan. 2024
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu File Operations finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
