matlab - 如何读取多个文本文件并根据文件名中的时间戳将它们合并在一起
问题描述
我有一个文件夹,其中包含许多文本文件,每个文本文件包含 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', ' '));
我怎样才能自动化这个过程?
解决方案
从文件夹中读取文本文件的过程可以通过使用循环并使用该函数检索所有.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);%
推荐阅读
- git - 变基后git提交的时间戳?
- python - 您需要选择具有所需厚度的对象
- google-apps-script - Google 表格脚本 - 复制整张表格保护
- binary-search-tree - python中的二叉搜索树在执行删除操作时找不到min_value
- php - 将自定义分类法中的 ACF 日期字段转换为时间戳
- verilog - 系统 Verilog 将向量 [10..0] 附加到整数
- python - 我想从较低的顺序对多列表进行排序,但我无法在一行中产生结果
- python - 不和谐.py | 如何获取调用命令的日期
- python-3.x - tweepy:Twitter 错误响应:在游标上执行 for 循环后状态代码 = 431
- object - 效果/Spark AR“错误:未定义不是函数”