copying file to a folder makes a new folder instead

hi, so i want my code to create a folder based on a list of file's names, but when i want to move the file to the folder i created, it made a new folder instead with the name of the variable i used. help please
I = the files
for gg = 1: numel(I)
bmp = {I.name}; %the files I want to move
bmp_n = char(bmp(gg));
for ii = 1: numel(Plist)
P = dir( fullfile( mainfolder,Plist{ii}, '*.dcm'));
dcm = {P(~[P.isdir]).name};
for jj = 1 : numel(dcm)
dicom = char(dcm(jj)); % converts cell to string
mkdir( parentfolder, dicom); % (dicom is the variable of the name of the new folders, the new
%folders' name are eg 00004, 00005)
ptt = digitsPattern + regexprep(dicom, '.dcm$', '') + "_";
matchedIdx = contains(bmp_n, ptt) % matching the name of the files to the name of the folder
if matchedIdx == true
copyfile input dicom % in this part it makes a new file dicom and move the files there instead of moving it to 00004, 00005, 00006 etc)
end
end
end
any help would be greatly appreciated!

1 Comment

copyfile input dicom %
is the command line form for copyfile -- "input" and "dicom" are interpreted as literal strings, not as variables. Also input is the builtin MATLAB function and should not be used as variable -- and it isn't defined in the above code otherwise.
copyfile(YOURWANTEDFILENAMEINVARIABLE,dicom)
where the first argument needs to be a variable that contains the matching file names in the matched pattern. You'll need to iterate over the number of elements that are TRUE in matchedIdx as copyfile isn't vectorized I do not believe.

Sign in to comment.

 Accepted Answer

Note that "myFolder" is the current folder storing the DCM files and the destination folders.
If they are in two different paths, then you may need to change the path:
cd(myFolder);
nfiles = dir(myFolder);
folders = {nfiles([nfiles.isdir]).name};
folders(1:2)=[];
files = dir(fullfile(myFolder,'*.dcm'));
filename={files.name};
for i = 1:length(filename)
matchedIdx = find(cellfun(@(x) contains(filename{i},x),folders));
copyfile(filename{i}, fullfile(myFolder,'\',folders{matchedIdx}));
end

11 Comments

i just have a question,what does this do?
folders(1:2)=[];
"folders" captures all the name of the directories in "myFolder" including {'.'} and {'..'}.
folders =
{'.'} {'..'} {'00001'} {'00002'} {'00003'} {'00004'} {'00005'} {'00006'}
folders(1:2)=[];
So folders(1:2)=[]; is going to remove these 2 cells, otherwise the code will be failed when finding the index "matchedIdx" if the file name contains a dot or two dots.
folders =
{'00001'} {'00002'} {'00003'} {'00004'} {'00005'} {'00006'}
Thank you! the copyfile still returns an error in my code, but i think it's more of a directory problem :)
Try the following:
DCM images are stored in "imagepath",
Folders are stored in "folderpath".
clear; clc;
imagepath='C:\SIMON\Machine\Analysis Figures';
folderpath='C:\SIMON\Machine\Analysis Figures\Folders';
nfolders = dir(folderpath);
folders = {nfolders([nfolders.isdir]).name};
folders(1:2)=[];
files = dir(fullfile(imagepath,'*.dcm'));
filename={files.name};
for i = 1:length(filename)
matchedIdx = find(cellfun(@(x) contains(filename{i},x),folders));
copyfile(fullfile(imagepath,filename{i}), fullfile(folderpath,'\',folders{matchedIdx}));
end
I'm very sorry to bother you, but somehow my code makes a folder with the name '\' and moves all the files i meant to move there. can you help me spot what i did wrong? it just said unknown error with copy file this time. for context, the file i'm interested is located in /users/.../Daniel/P1 until P20 so i had to use a loop to extract all the dicom files under it. the folder i want to move the dicom files into is the nufolder. in the loop i made a folder for every dicom file name under nufolder, that's where i want to move the files into.
%change file path here :
mainfolder ='/Users/sesiliamaidelin/Downloads/summer project/CL2 Dicom/Daniel';%dicom images
parentfolder = '/Users/sesiliamaidelin/Downloads/summer project/';
mkdir nufolder;
parentfolder = '/Users/sesiliamaidelin/Downloads/summer project/nufolder';
P_f = dir( fullfile( mainfolder, '*'));
%Plist = setdiff({ P_f([P_f.isdir]).name},{'.','..'}); % works fine up to here
Plist = {P_f([P_f.isdir]).name};
Plist(1:2)=[];
bmp_path = '/Users/sesiliamaidelin/Downloads/summer project/input';
I = dir(fullfile(bmp_path,'*.bmp'))
Ilist = {I.name};
%I = dir( fullfile( input, '*'))
%%
for ii = 1: numel(Plist)
P = dir( fullfile( mainfolder,Plist{ii}, '*.dcm'));
dcm = {P(~[P.isdir]).name}; % works great!! gets all the dicom file in the p files
for jj = 1 : numel(dcm)
[filepath, name, ext]= fileparts(dcm(jj)); % converts cell to string
mkdir( parentfolder, name); % makes folders after the dcm names in nufolder
end
matchedIdx = find( cellfun(@(x) contains(name,x),dcm));
copyfile(fullfile(mainfolder, dcm{jj}), fullfile(parentfolder, '\', Plist{matchedIdx}))
end
"i just have a question,what does this do? folders(1:2)=[];"
That is an anti-pattern, buggy attempt to remove the dot directories from the array.
Your original approach using SETDIFF is the correct, robust, recommended way to remove those directory names. You could alternatively use ISMEMBER or something similar.
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
If one creates the dir() list by a pattern-matching file specification, one can preclude the return of the two spurious entries in the first place...
Albeit it is undocumented behavior in MATLAB dir(), Windoes NTFS partitons by default return files sorted by name; I've yet to see any other behavior from dir() albeit again code should not rely on such behavior to be the most robust and to be generic across platforms and possible changes in future behavior.
Modify the code again and hope it help.
clear; clc;
mainfolder ='C:\SIMON\Machine\Figures\CL2 Dicom\Simon'; % Subfolders contains dicom images
parentfolder = 'C:\SIMON\Machine\Figures'; % Working directory
mkdir nufolder; % Create nufolder under working directory
nufolderpath = 'C:\SIMON\Machine\Figures\nufolder'; % Define the path name of nufolder
filesAndFolders = dir([mainfolder '/**']); % Get all subfolder and files names
alllist={filesAndFolders.name}; % Convert to cell
dcmidx = cellfun(@(x) contains(x,'.dcm'),alllist); % Index to extract dicom files only
dcmlist = alllist(dcmidx); % List of dicom files only
dcmpath = {filesAndFolders(dcmidx).folder}; % Extract the path of each dicom files
for jj = 1 : numel(dcmlist)
[filepath, name, ext]= fileparts(dcmlist(jj)); % Extract file name
mkdir(nufolderpath, name); % makes folders after the dcm names in nufolder
copyfile(fullfile(dcmpath{jj},'\',dcmlist{jj}), fullfile(nufolderpath, '\', name)) % Copy file directly and so string comparison is needed
end
Left one is the folders and files location before running the script.
Right one is the result after running the script.
At some point I found (and posted) a reference indicating that NTFS reads the Locale information of the person who created the NTFS file system, and locks the sorting order appropriate for that Locale into the filesystem.
For example, many many PC users use Windows-1252, which is like a superset of ISO-8896-1 . It has associated sorting rules, and those sorting rules are different than the rules mandated by Unicode . I personally never use Windows-1252: I always go for en-CA (English, Canada) locale, which uses UTF-8 by default. Someone who was using an NTFS filesystem created under Windows-1252 could get a different sorting order than I would get for creating exactly the same files in exactly the same order under en-CA . Furthermore if I change locale to create a second filesystem, then if I were to copy the same files to the two different filesystems, then the sort order could end up different for the two filesystems.
Apple has not been perfect either. The sorting order they used for filesystems before OS-X changed when HFS was put into use. HFS's rules for canonicalization of names were broken, and were changed, with (if I recall correctly) the change going into effect for the HFS+ . Some people consider HFS+'s canonicalization to also be broken, so the newer APFS filesystem has slightly different rules yet, if I understand correctly. On the other hand, it is the case that two different people who create HFS+ filesystems should get the same sort order no matter what locale they were using.
it works nicely, thank you! :)

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!