renaming and deleting files consecutively by matlab
TRANSCRIPT
Jans Hendry / UGM Indonesia 2011
[1]
RENAMING AND DELETING FILES CONSECUTIVELY BY MATLAB
Reading a single file from your directory by matlab is easy to do. Take an example when it’s an image,
just put ‘filename’ as variable that contains your image name and save the m.file into same directory. Its
not a big problem, I guess.
There is a case when we deal with great amount of files to process by matlab. Imagine when all your files
have different name at each. Then what you have to do is to rename the files one by one manually. Of
course, it become a big problem indeed non-technical problem but all you further works depend on it.
Surely it is very troublesome.
In this section, I will give a technique to solve such problem above. This problem has become big issues,
often my friends ask me how to solve it. Actually, it’s a tricky. You could use your creativity and improve
many techniques in order to solve this problem. I will show you an effective way how to do it.
- Read all files in the directory
- Decide filename you would use
- Save all files with new filename
But you have to make sure that all files already in desired sequences. Let’s move on to matlab codes.
- Read all files in the directory
files = dir('*.*')
result:
files =
15x1 struct array with fields:
name
date
bytes
isdir
datenum
explaination:
well, that single code ask matlab to read amout files in current directory. You can see that it
contains 15 files with vary extension. The question is, what will be the code if I want to initialize
only image data *.jpg images.
files = dir('*.jpg');
Jans Hendry / UGM Indonesia 2011
[2]
result:
files =
9 x1 struct array with fields:
name
date
bytes
isdir
datenum
You can see that we have only 9 jpeg files.
In order to check single file, please type in command window:
>> files(3).name
ans =
168200_1620314784076_1122625896_31497559_3456887_n.jpg
>> files(end).name
ans =
188469_1669531534464_1122625896_31579471_5299028_n.jpg
- Deciding filename we’ll use
In this case I will change all filename to ‘image.jpg’.
- Save all files with new filename
In this step, we are gonna use looping rule. Because we have more than one file. Renamed file
will be kept in subfolder called renamed. Remember, you have to avail this subfolder before
executing.
for ii=1:numel(files) I=imread(files(ii).name); imwrite(I,['renamed\' sprintf('image%d.jpg',ii)]); end
Jans Hendry / UGM Indonesia 2011
[3]
result:
Before:
Its easy huh? ☺
But what about if I want to keep renamed files in the same folder with m.files or we could say in
the current directory? Also, I want to delete all the old files (images only) simultaneously?
Try this codes:
for ii=1:numel(files) filename=files(ii).name; I=imread(filename); imwrite(I,sprintf('image%d.jpg',ii)); delete(filename); end
Jans Hendry / UGM Indonesia 2011
[4]
of course it will delete your files permanently from computer.
Here is the final result:
~~ THANKS A LOT ~~