从多个文本文件中读取值并将其全部写入另一个文件

时间:2018-01-18 15:47:49

标签: matlab file-io text-files fopen overwrite

我有一个子文件夹列表,每个子文件夹都有一个名为simass.txt的文本文件名。从每个simass.txt文件中,我提取c{1}{2,3}单元格数据(如下面的代码所示),并在单列中以顺序形式将其写入文件名features.txt

我遇到一个问题,最后我在features.txt中只有一个值,我认为这是由于值被覆盖。我应该在features.txt中拥有1000个值,因为我有1000个子文件夹。

我做错了什么?

clc;    % Clear the command window.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
% Define a starting folder wherever you want
start_path = fullfile(matlabroot, 'D:\Tools\Parameter Generation\');
% Ask user to confirm or change.
topLevelFolder = uigetdir(start_path);
if topLevelFolder == 0
  return;
end
% Get list of all subfolders.
allSubFolders = genpath(topLevelFolder);
% Parse into a cell array.
remain = allSubFolders;
listOfFolderNames = {};
while true
[singleSubFolder, remain] = strtok(remain, ';');
if isempty(singleSubFolder)
    break;
    end
listOfFolderNames = [listOfFolderNames singleSubFolder];
end
numberOfFolders = length(listOfFolderNames)
% Process all text files in those folders.
for k = 1 : numberOfFolders
% Get this folder and print it out.
thisFolder = listOfFolderNames{k};
fprintf('Processing folder %s\n', thisFolder);

% Get filenames of all TXT files.
filePattern = sprintf('%s/simass.txt', thisFolder);
baseFileNames = dir(filePattern);
numberOfFiles = length(baseFileNames);
% Now we have a list of all text files in this folder.

if numberOfFiles >= 1
    % Go through all those text files.
    for f = 1 : numberOfFiles
        fullFileName = fullfile(thisFolder, baseFileNames(f).name);
      fileID=fopen(fullFileName);
      c=textscan(fileID,'%s%s%s','Headerlines',10,'Collectoutput',true);
      fclose(fileID);
      %celldisp(c)   % display all cell values
      cellvalue=c{1}{2,3} 
      filePh = fopen('features.txt','w');
      fprintf(filePh,cellvalue);
      fclose(filePh);
        fprintf('     Processing text file %s\n', fullFileName);
    end
else
    fprintf('     Folder %s has no text files in it.\n', thisFolder);
end
end

1 个答案:

答案 0 :(得分:4)

问题在于您在fopen中使用的权限。来自documentation

  

'w' - 打开或创建新文件进行编写。 丢弃现有内容(如果有)。

这意味着您每次都要丢弃内容,而最终只有最后一个值。最快的修复方法是将权限更改为'a',但我建议在代码中添加一些更改,如下所示:

  1. 在循环之前创建cellvalue,并将c{1}{2,3}读入此新的向量/单元格数组。
  2. 完全填充cellvalue后执行一次写入操作。
  3. cellvalue = cell(numberOfFiles,1);
    for f = 1 : numberOfFiles
        ...
        cellvalue{f} = c{1}{2,3};
    end
    fopen(...);
    fprintf(...);
    fclose(...);