【问题标题】:Read a value from multiple text files and write all into another file从多个文本文件中读取一个值并将其全部写入另一个文件
【发布时间】:2018-06-27 18:07:47
【问题描述】:

我有一个子文件夹列表,每个子文件夹都有一个名为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

【问题讨论】:

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


    【解决方案1】:

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

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

    这意味着您每次都丢弃内容,并且最终只获得最后一个值。最快的解决方法是将权限更改为'a',但我建议对代码进行一些更改,如下所示:

    1. 在循环之前创建cellvalue,并将c{1}{2,3} 读入这个新的向量/元胞数组。
    2. 在cellvalue 完全填充后执行一次写入操作。

    cellvalue = cell(numberOfFiles,1);
    for f = 1 : numberOfFiles
        ...
        cellvalue{f} = c{1}{2,3};
    end
    fopen(...);
    fprintf(...);
    fclose(...);
    

    【讨论】:

    • @AnderBiguri 抱歉,免费托管的缺点...我无能为力。
    • @am304 别担心,只是给你提示
    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 2015-12-29
    • 1970-01-01
    • 2016-08-14
    • 2023-04-05
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多