Sorting a directory of txt files.

7 次查看(过去 30 天)
Samuel
Samuel 2013-5-11
编辑: Stephen23 2021-4-18
Hello, I am trying to sort out a list of txt files I have in a certain directory, so they can be loaded in order one at a time. For example, in my directory are a numerically ordered list of txt files: 800.txt,900.txt,1000.txt,1200.txt,total.txt,etc.
I want to load just the number files in ascending order. I noticed that just using the ls command directory will sort out by the first numerical digit, not taking account of the digits, and therefore not making it truly numerically ascending.
Here is the portion of the code I am running:
cd('c:\directory');
list=ls('*.txt')
%this is the routine to load the txt file itself. in example, the fifth file.
y=load(list(5,:));
I read up on this article involving the ASCII ascending and how a separate routine needs to be separately written to manually ascend it. However, this method will involve the creation of a cell array, and the load command didn't work on the file list generated: http://www.mathworks.com/support/solutions/en/data/1-OGU22/index.html?product=ML
Any help involving this problem will be appreciated. Thanks
  2 个评论
Stephen23
Stephen23 2016-2-22
编辑:Stephen23 2021-4-18
My FEX submission natsortfiles was written to deal with this exact problem:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

请先登录,再进行评论。

回答(3 个)

Yao Li
Yao Li 2013-5-13
Implement dir to list all the file names in the specific directory.
Use if-else to find the number files (char(48) to char(57))
Implement sort(xxx,'ascend') to sort the elements in ascending order

Jan
Jan 2013-5-13
编辑:Jan 2013-5-13
list = dir(fullfile(C:\directory', '*.txt'));
list = list(~[list.isdir]); % Exclude folder with matching name
name = {list.name};
str = sprintf(name, '%s*');
num = sscanf(str, '%d*');
[dummy, index] = sort(num);
name = name(index); % Sorted numerically now
for iName = 1:length(name)
y = load(name{iName});
...
end

Stephen23
Stephen23 2016-2-22
编辑:Stephen23 2021-4-18
My FEX submission natsortfiles was written to deal with this exact problem:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by