首页 > 技术文章 > MATLAB检查指定路径中的子文件夹中的文件名中是否带有空格

go-better 2017-07-19 21:53 原文

测试文件夹为:

clear;close all;clc;
%%
%程序实现的功能
%检查指定路径中的子文件夹中的文件名中是否带有空格,并去掉文件名中的空格
%%
%程序中用到的之前不清楚的函数如下
%1)strfind(a,b):即找a中是否有b,如果a中有b,则输出b的位置序号。没有输出空数组
%2)isempty(a):判断数组是否为空
%3)strrep(a,b,c):就是把a中所有出现的b换为c
%4)movefile(a,b):a移动为b,如C:\test1.jpg移动为C\test2.bmp
%%
tic;
disp('程序开始执行');
%%%%%%需要更改的参数(即文件夹路径)%%%%%%%%%%%%%%%%%%%%%%%%%%

path='C:\Users\yangsu\Desktop\test2';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count=0;%用于统计总共找到几个文件名错误的文件
dirList=dir(path);%读取文件夹列表,这种方式读取会保留原文件.(在结构体中第一个)和上一层目录..(在结构体第二个)
countList=length(dirList);%文件夹个数
fid = fopen([path,'\','errorlist.txt'], 'w');%打开数据文件夹时,对应的错误文件名输出列表
for numList=3:countList%文件夹从3开始
%     if(length(dirList(numList).name)>=2)%根据这个过滤掉在此文件夹可能存在的txt文件
%         continue;
%     end
    fileName=dir([path,'\',dirList(numList).name]);%读取子文件夹
    fileSum=length(fileName);%统计子文件夹中的文件个数
    disp(['开始搜索文件夹',dirList(numList).name]);
    for fileNum=3:fileSum%文件从3开始
        judge=strfind(fileName(fileNum).name,' ');
        if isempty(judge)
            continue;
        else
            fprintf(fid,'%s', '找到的含有空格的文件为:');
            fprintf(fid,'%s', [dirList(numList).name,'/',fileName(fileNum).name]);%输入:子文件/图片名称
            fprintf(fid,'\n');%换行
            count=count+1;
            disp(['找到一个带有空格的文件,文件完整路径为',' ',dirList(numList).name,'/',fileName(fileNum).name]);
            %后来想到添加的功能找到了带有空格的文件,把这个文件的文件名中的空格去掉作为一个新的文件名保存
            newFileName=strrep(fileName(fileNum).name,' ','');
            fprintf(fid,'%s', '修改后的文件为:');
            fprintf(fid,'%s', [dirList(numList).name,'/',newFileName]);%输入:子文件/图片名称
            fprintf(fid,'\n');%换行
            fprintf(fid,'\n');%换行
            fulloriginalname=[path,'\',dirList(numList).name,'\',fileName(fileNum).name];
            fullchangename=[path,'\',dirList(numList).name,'\',newFileName];
            movefile(fulloriginalname,fullchangename);
            disp(['去除文件名中的空格后,文件完整路径为',' ',dirList(numList).name,'/',newFileName]);
            disp(' ');
        end
    end
end
fclose(fid);%关闭文本文件
fclose('all');%关闭所有连接,防止没关掉的情况
disp(['程序执行完毕','总共找到',' ',num2str(count),' ','个文件名中带有空格的文件']);
toc;

matlab输出窗口:

并生成一个errorlist.txt,记录修改信息。

修改后原来含有空格的文件名没有空格了。

 

推荐阅读