Rename File in a Different Folder

Hey all,
I am trying to use the movefile command to rename a file using variables and current date.
If I use this code and the REPORT.txt is located in the working folder, it works absolutely fine:
movefile('REPORT.txt', fullfile(prjNo + 'REPORT'+ date +'.txt'));
However, the file I am trying to rename is located in a subfolder of the working folder. I have tried the following options but none of them works:
% Option 1:
movefile('OUT\REPORT.txt', fullfile(prjNo + 'REPORT'+ date +'.txt'));
% Option 2:
movefile(fullfile(workingfolder, + 'OUT\REPORT.txt'), fullfile(prjNo + 'REPORT'+ date +'.txt'));
Can someone point out where the problem is or offer an elegant alternative solution please?
Many thanks.

7 Comments

movefile('REPORT.txt', fullfile(prjNo + 'REPORT'+ date +'.txt'));
% Is this ^^^^^^^^ a highly obfuscated way to avoid calling CHAR() ?
Why not just use SPRINTF or any other usual methods to convert numeric to text?
What is the name of the subfolder? (you used both "RUN" and "OUT" in your examples).
I don't know any better way of doing it than fullfile.
Sorry about the confusion regarding the subfolder, it is called OUT. I have corrected the post.
I don't think you fully understand how fullfile works. It will put your separate inputs together to form a valid path string, taking the difference between Unix/Linux/Mac and Windows into account.
You only provided a single input. Inputs in Matlab are not separated by the plus symbol, but with a comma symbol.
You should use sprintf to create the name of the file, then use fullfile to combine the file name and folder names.
Thanks. That is correct. I may not understand it fully yet.
I have come up with this based on your input guys:
workingfolder=pwd;
DateFormat = 'yyyy.mm.dd'; % Define date format
date=datestr(now,DateFormat);
newfilename = strcat(prjNo,'_REPORT_',date,'.txt');
movefile(fullfile(workingfolder,'OUT','REPORT.txt'),fullfile(workingfolder,'OUT',newfilename))
It works but I am wondering if there is a better way to go about this problem?
Is the variable prjNo numeric or text ?
I personally would prefer sprintf instead of strcat, but this is equivalent to what I would suggest.
Note that explicitly including the working directory is not required.

Sign in to comment.

 Accepted Answer

Stephen23
Stephen23 on 4 Nov 2022
Edited: Stephen23 on 4 Nov 2022
new = fullfile(prjNo + 'REPORT'+ date +'.txt'); % odd use of FULLFILE.
movefile(fullfile('.','OUT','REPORT.txt'),fullfile('.','OUT',new))
Note that '.' refers to the current directory.

More Answers (0)

Categories

Products

Release

R2021b

Asked:

on 4 Nov 2022

Commented:

Rik
on 4 Nov 2022

Community Treasure Hunt

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

Start Hunting!