Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How do I search a directory for an already existing file name and if it is present, save a new file name the same as the old one but with an iteration number at the end of it?

1 ビュー (過去 30 日間)
Tyler Hewitson
Tyler Hewitson 2018 年 9 月 24 日
終了済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello,
I am wondering if anybody could help me out with my problem? I am trying to search a directory for an existing file name and if it exits, save a new file with the existing file name but with an iteration number after it. For example I have a file called 'processed_results_Br0' and I want to save a new file as 'processed_results_Br0_RUN1' if the file exists. I have written the following code in an attempt to implement what I am describing:
dir_string = 'C:\Ripple\';
mkdir (dir_string);
output_file_name = ['processed_results_' name_str];
filesAndFolders = dir(dir_string);
for i=1:length(filesAndFolders)
if ~isempty(strfind(filesAndFolders(i).name,output_file_name))
run_index = strfind(filesAndFolders(i).name,'_RUN');
if ~isempty(run_index) && (filesAndFolders(i).name(end) ~= 'N')
run_iteration = i
else
display('Test');
run_iteration = filesAndFolders(i).name(run_index+4);
end
end
end

回答 (2 件)

Fangjun Jiang
Fangjun Jiang 2018 年 9 月 24 日
How about use some of the functions?
fullfile()
exist(..,'file')
copyfile()

Bish Erbas
Bish Erbas 2018 年 9 月 24 日
編集済み: Bish Erbas 2018 年 9 月 24 日
curDir = pwd;
files = dir(curDir);
files = files(~ismember({files.name},{'.','..'}));
fileToSearch = 'processed_results.dat';
for k = 1:length({files.name})
idx = cellfun(@ (x) strcmp(x,fileToSearch), {files.name});
myFullFile = fullfile(curDir,files(idx).name);
copyfile(myFullFile,[myFullFile '_RUN1']);
end

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by