2011-10-22 19 views
0

有沒有辦法簡單地加載目錄中的第一個文件的名稱,而不指定它的名稱,然後在每次迭代中移動到目錄中的下一個文件?如何在一個循環中從文件移動到文件,MatLab?

我有文件名用1,1.5,2,2.5,3,3.5結尾等命名的問題......所以在迭代中的num2str(X)將無助於定位文件。

我想重命名他們使用strrep(s1,s2,s3),但我又遇到了同樣的問題加載到一個循環!

我知道我應該先用更多計劃命名它們,但這些文件太大而無法再次運行模擬。

這是我必須重命名文件:

%%%RENAMING A FILE%%% 

%Search directory to get number of files 
d1=dir('\MATLAB\Data\NumberedQwQoRuns'); 
numfiles = length(d1)-2; 


for a=1:numfiles 
%Search subdirectory if necessary for count of those folders 
d2=dir('\MATLAB\Data\NumberedQwQoRuns\Run'num2str(a)); 
subdir = length(d2)-2; 
for b= 1:subdir 

origname= PROBLEM??? 

Newname=['Zdata' num2str(b) '.txt'] 
Newfile= strrep(origname, origname, newname) 
movefile(origname,Newfile) 

end 
end 

非常感謝你的幫助, 阿比德一個

回答

2

這裏是我的解決方案:

%# get runs subdirectories 
BASE_DIR = '/path/to/Runs'; 
runsDir = dir(fullfile(BASE_DIR,'Runs')); 
runsDir = {runsDir([runsDir.isdir]).name};   %# keep only directory names 
runsDir = runsDir(~ismember(runsDir, {'.' '..'})); %# ignore "." and ".." 

for r=1:numel(runsDir) 
    %# get files in subdirectory 
    runFiles = dir(fullfile(BASE_DIR,'Runs',runsDir{r},'*.txt')); %# *.txt files 
    runFiles = {runFiles.name};         %# file names 

    %# map filenames: 1,1.5,2,2.5,... into 1,2,3,4,... 
    [~,ord] = sort(str2double(regexprep(runFiles,'\.txt$',''))); 
    newrunFiles = cellstr(num2str(ord(:),'Zdata_%d.txt')); 
    newrunFiles = strtrim(newrunFiles); 

    %# rename files 
    for f=1:numel(runFiles) 
     fname = fullfile(BASE_DIR,'Runs',runsDir{r},runFiles{f}); 
     fnameNew = fullfile(BASE_DIR,'Runs',runsDir{r},newrunFiles{f}); 
     movefile(fname,fnameNew); 
    end 
end 

我測試了以下文件結構:

Runs/ 
| 
|__Run1/ 
| |__1.txt  will become: Zdata_1.txt 
| |__1.5.txt     Zdata_2.txt 
| |__2.txt      Zdata_3.txt 
| |__2.5.txt     etc... 
| |__3.txt 
| |__3.5.txt 
| 
|__Run2/ 
    |__1.txt 
    |__1.5.txt 
    |__2.txt 
    |__2.5.txt 
    |__3.txt 
    |__3.5.txt 
+0

謝謝大家的幫助,有很多在這裏使用的新方法,但它非常大,所以我可以學習它們。然而,當我運行腳本時,我得到一個錯誤(???錯誤:文件:Altrenamefile.m行:13列: 7)我真的不明白什麼是錯的。表達式或語句不正確 - 可能是 不平衡({,或[。 – Abid

+0

@Abid:我認爲它是調用:'[〜,ord] = sort(...)'。運算符](http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/)是在MATLAB R2009b中引入的,所以如果你有舊版本,替換它與一個虛擬變量(這意味着我們不關心該值,並希望忽略它):'[dummy,ord] = sort(...)' – Amro

+0

我認爲我很難理解或正確設置路徑。在文件NumberedQwQoRuns中,我有這些文件:Run1,Run2,... Run9。在這些文件中有我想重命名的.txt文件。謝謝你,Abid – Abid

0

獲得從subdir(b).name

注意實際的文件名,你可能如果您的綜合名稱與現有名稱之一匹配,則會出現問題。

相關問題