【问题标题】:How to get the name of the parent folder of a file specified by its full path?如何获取由其完整路径指定的文件的父文件夹的名称?
【发布时间】:2014-04-25 21:33:54
【问题描述】:

在 Matlab 中,我有一个包含文件路径的字符串:

path = 'C:/Data/Matlab/Dir/file.m'

我现在想提取字符串的“Dir”部分。一种方法是:

[first, second, third, fourth, fifth] = strtok(path, '/')

然后取fourth 元素,最后从中删除第一个字符(/)。

我只是想知道是否有更优雅的解决方案?必须显式存储所有 first ... fifth 元素然后手动删除 / 似乎有点麻烦。

谢谢。

【问题讨论】:

    标签: matlab string-parsing


    【解决方案1】:

    试试:

    parts = strsplit(path, '/');
    DirPart = parts{end-1};
    

    【讨论】:

      【解决方案2】:

      试试

      s = regexp(path, '/', 'split')
      s(4)
      

      如“使用拆分关键字在分隔符处拆分字符串”中的 here 所述。

      【讨论】:

        【解决方案3】:

        如果您不想关心路径的元素数量,并且不想使用旧版本的 Matlab 中不可用的strsplit,您也可以使用这一行:

        directory = getfield( fliplr(regexp(fileparts(path),'/','split')), {1} )
        
        %% or:
        % alldir = regexp(fileparts(path),'/','split')
        % directory = alldir(end)
        

        这将始终返回指定文件的父文件夹。

        您还应该考虑使用filesep 而不是'/' 以获得与各种系统的更好兼容性。

        【讨论】:

          【解决方案4】:

          还有老办法……

          n=size(path,2);
          
          while path(n)~='/'; n=n-1; end
          
          i=n-2;
          
          while path(i)~='/'; i=i-1; end
          
          % result
          path(i+1:n-1)
          

          【讨论】:

            【解决方案5】:

            Max 解决方案适用于 Windows,但在 linux/mac 上可能会由于绝对路径开头的斜线而失败。我的建议是:

            parts = strsplit(path, filesep);
            DirPart = parts{end-1};
            if path(1) == filesep
                DirPart = [filesep,DirPart];
            end
            if path(end) == filesep
                DirPart = [DirPart,filesep];
            end
            

            【讨论】:

              【解决方案6】:

              如果不知道有多少个文件夹分层,用一行代码找到父目录

              fliplr(strtok(fliplr(pname),'\'))
              

              【讨论】:

                【解决方案7】:

                你可以试试fileparts函数如下:

                [ParentFolderPath] = fileparts('C:/Data/Matlab/Dir/file.m');
                [~, ParentFolderName] = fileparts(ParentFolderPath) ;
                ParentFolderName = 'Dir'
                

                【讨论】:

                  【解决方案8】:
                  parts = strsplit(file_path, filesep);
                  parent_path = strjoin(parts(1:end-1), filesep);
                  

                  【讨论】:

                    猜你喜欢
                    • 2011-04-13
                    • 2011-07-10
                    • 2016-01-31
                    • 2016-12-29
                    • 2021-01-06
                    • 1970-01-01
                    • 2011-08-30
                    • 1970-01-01
                    • 2015-06-15
                    相关资源
                    最近更新 更多