Using a loop to change the source path and rename each file
4 ビュー (過去 30 日間)
古いコメントを表示
Hi. So I wrote the following functinal code to rename one file from one particular path. I have 38 paths to which I would like to do this, i.e. p1 would be p2 then p3 then p4... and pdest would be the same for all source paths (p1-p38). The filename is also always the same ('myfile.dat'). How would I be able to use a loop to change p1 to p2,p3,p4... and the new filename to 2.myfile.dat, 3.myfile.dat and so on.
Summarising:
- p1 changes to p2, p3, p4. ..
- newname changes to 2myfile.dat, 3myfile.dat, 4myfile.dat ...
- pdest is always the same
- filename is always the same
% Paths (only p1 listed, there are 38)
p1 = 'path1_source';
pdest = 'pathdestination'
% Finding file in source and copying in destination
filename = 'myfile.dat';
source = fullfile(p1,filename);
destination = fullfile(pdest,filename);
copyfile(source,destination)
% Renaming file
oldname = filename;
newname = '1myyfile.dat'; % added 1 in front
copyfile(oldname,newname);
% Deleting old file
delete(filename)
0 件のコメント
回答 (1 件)
Image Analyst
2018 年 11 月 18 日
In some loop over k,
newname = sprintf('%d%s', k, filename); % Prepend the loop iteration variable to the filename.
where filename is the input filename that changes on every iteration. See The FAQ for more explicit code samples.
Most people would use movefile() to rename or move files.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!