首页 > 解决方案 > 如何读取多个文本文件并根据文件名中的时间戳将它们合并在一起

问题描述

我有一个文件夹,其中包含许多文本文件,每个文本文件包含 6 个标题以及我要读取的数据:

Phone timestamp;sensor timestamp [ns];channel 0;channel 1;channel 2;ambient
2021-02-15T12:37:32.401;536755331722174808;485232;501982;494303;16818;
2021-02-15T12:37:32.408;536755331729573094;485244;501970;494199;16770;
2021-02-15T12:37:32.415;536755331736971380;485235;502069;494234;16735;

文件名的格式为“Data_20210213_120806” Data_ YYMMDD_HHMMSS,. 目前,我刚刚使用手动读取数据uigetfile并以正确的顺序(最早日期->最新日期)选择文件并将每个文件连接在一起。

当我只有几个文件要查看时这很好,但当存在大量文件时不是很实用。我想知道是否有一种方法可以自动读取每个文件(根据文件名中的日期以正确的顺序)并将它们合并到一个 N × 6 矩阵中。

手动读取数据的代码:

[filename1,pathname1] = uigetfile('*.txt','Please Choose the file to process');
filepath1 = fullfile(pathname1,filename1);
fileCell1= readcell(filepath1,'FileType','text','Delimiter',';');

% Define Structure.
Table = cell2table(fileCell1(2:end, :), 'VariableNames', fileCell1(1, :));

% Convert to Datetime
Table.("Phone timestamp") = datetime(strrep(Table.("Phone timestamp"), 'T', ' '));

我怎样才能自动化这个过程?

标签: matlabfile-io

解决方案


从文件夹中读取文本文件的过程可以通过使用循环并使用该函数检索所有.txt文本文件名来完成。dir()如果可以提供示例文本文件的内容,则可以显示示例合并过程。

clc;

%Grabbing all the text files in a folder named "Text Files"%
Folder_Name = 'Text Files';
%Asterisk, * used to indicate any prefix/wildcard is allowed%
Text_Files = dir(fullfile(Folder_Name,'*txt'));
File_Names = {Text_Files.name}.';

Date_Num_Representation = zeros(1,length(File_Names));

Format = 'yyyy-mm-dd HH:MM:SS';
for File_Index = 1: length(Text_Files)
    Name = erase(File_Names(File_Index),"Data_");
    Name = erase(Name,".txt");
    Name = char(strrep(Name,"_"," "));
    Name = Name(1:4) + "-" + Name(5:6) + "-" + Name(7:8) + Name(9:11) + ":" + Name(12:13) + ":" + Name(14:end);
    Date_Num_Representation(File_Index) = datenum(Name,Format);
end

[~,Indices] = sort(Date_Num_Representation);

Combined_Table = [];
for File_Index = 1: length(Text_Files)
Sorted_Index = Indices(File_Index);
Path = fullfile(Folder_Name,Text_Files(Sorted_Index).name);
New_Table = readtable(Path);
New_Table = New_Table(:,1:6);
Combined_Table = [Combined_Table; New_Table];
end

Combined_Table.Properties.VariableNames = {'Phone timestamp','sensor timestamp [ns]','channel 0','channel 1','channel 2','ambient'};
Combined_Table

%Might be useful%
%Combined_Table = table2cell(Combined_Table);%

推荐阅读