Renaming files in directory that meet array criterion

1 visualizzazione (ultimi 30 giorni)
g
g il 2 Nov 2019
Commentato: g il 2 Nov 2019
Let's say I have some files in a directory my_directory:
file_23.txt
file_35.txt
file_37.txt
I'm reading the files through
my_files = dir(fullfile(my_directory,'file_*.txt'))
and let's say I have an array my_array, which contains some values:
23
37
I want to rename the files with numbers matching the numbers in the array, by doing something along the lines of
for i = 1:length(my_array)
j=my_array(i)
% rename each appropriate file in my_directory here to file_j_new.txt
end
So in the end I want my_directory to contain
file_23_new.txt
file_35.txt
file_37_new.txt
How do I do this, keeping in mind that the files are in a different directory?

Risposte (1)

KALYAN ACHARJYA
KALYAN ACHARJYA il 2 Nov 2019
Modificato: KALYAN ACHARJYA il 2 Nov 2019
Try?
text_files=dir('C:\complete_path_text_files\*.txt');
outDirectory='C:\complete_path_to save_txt_files\';
array_data=[.........];
% Please note that array length must be same or greater the length of text_files
for i=1:length(text_files)
textfile=strcat('C:\complete_path_text_files\',text_files(i).name);
writetable(textfile,strcat(outDirectory,text_files(array_data(i)).name));
end
Or in the same directory to create new file
textfiles=dir('*.txt');
array_data=[........];
for ii=1:length(textfiles)
filename=textfiles(ii).name;
file1=importdata(filename);
writetable(file1,strcat(filename_(array_data(i)).name));
%............................^ May be minor change required here
end
Please note, I did not try the code, I wrote here based on my images call and write concept.
Hope it helps!
  5 Commenti
KALYAN ACHARJYA
KALYAN ACHARJYA il 2 Nov 2019
Suppose you have planning to rename the three text files
text1
text2
text3
And you want to add some number at last of the file name as per following array
array=[23 47] % Having length 2
Then, files name becomes
text1_23
text2_47
and
text3_??? %Now what next
In the repeat or?
g
g il 2 Nov 2019
I want to rename the files
file_23.txt
file_35.txt
file_37.txt
with the array
23
37
to
file_23_new.txt
file_35.txt
file_37_new.txt

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by