文件查找
首先确定数据存储的文件夹地址,记为folder_dir。如果该文件夹不存在需要访问的子文件夹,则直接复制文件地址;如果存在需要访问的子文件夹,则要利用dir函数进行寻找,将子文件夹信息用subdir进行存储。
// 文件查找1
folder_dir = 'D:\1010_没红标的雷达板标定\fy\';
subdir = dir(folder_dir);
图1 folder_dir展示
|
图2 subdir展示
|
dir( )函数获得指定文件夹下的所有子文件夹和文件,并存放在结构体数组中。图2subdir中的name是folder_dir所示文件夹下所有子文件夹和文件的名称,folder就是路径索引,data是子文件夹创建的时间,datenum是创建时间的数值表示,可以通过比较多个文件的datenum知道文件创建的先后顺序。
值得注意的是,subdir前两行分别是’.‘和’…',是因为该函数会返回当前目录(“.”)和上一级目录(“…”),可以在读取subdir内容时跳过。这里我想找的是子文件夹下所有后缀为.dat的文件,所以代码如下。
// 文件查找2
for i = 1 : length( subdir )
if( isequal( subdir( i ).name, '.' )||isequal( subdir( i ).name, '..')) % 如果是目录则跳过
continue;
end
subdirpath = fullfile( folder_dir, subdir( i ).name, '*.dat' );
dat = dir( subdirpath ); % 子文件夹下找后缀为dat的文件
end
图3 子文件夹
|
图4 子文件夹下的所有dat文件
|
或者直接使用dir( )函数返回所后缀为.dat的文件。
// 文件查找2
a = dir('*.dat'); // 返回当前文件夹下所有的dat文件
b = dir('**/*.dat'); // 返回当前文件夹和下一级文件夹中所有的dat文件
文件移动和改名
把旧路径存储在old_path中,新路径存储在new_path中,重命名为newname。需要注意的是,利用fullfile获得的路径tmp,是没有最后的" \ “,如果直接带入copyfile( )函数,会无法进行数据读取。所以进行了字符串合并,在后面加了一个” \ "。
// 文件移动和改名
for i = 1 : length( subdir )
if( isequal( subdir( i ).name, '.' )||isequal( subdir( i ).name, '..')) % 如果是目录则跳过
continue;
end
subdirpath = fullfile( folder_dir, subdir( i ).name, '*.dat' );
dat = dir( subdirpath ); % 子文件夹下找后缀为dat的文件
tmp = fullfile( folder_dir, subdir( i ).name);
old_path = [tmp '\'];
for j = 1 : length( dat )
datpath = fullfile( folder_dir, subdir( i ).name, dat( j ).name);
newname = sprintf('%s_%d.dat',subdir(i).name,j);
copyfile([old_path dat( j ).name],[new_path,newname])
end
end
所调用函数功能
1. dir( )函数
官方函数解释: https://ww2.mathworks.cn/help/matlab/ref/dir.html
2. fullfile( )函数
官方函数解释: https://ww2.mathworks.cn/help/matlab/ref/fullfile.html
4. copyfile( )函数
官方函数解释: https://ww2.mathworks.cn/help/matlab/ref/copyfile.html