Change file header and save the file -- do this for all files in directory.
조회 수: 6 (최근 30일)
이전 댓글 표시
Hello MatLab Community,
I need help with some data text files. I have various text files with different names. I want to load each file into MatLab and change the first line (headers) in each file (so they all end up with the same headers) and then save the file.
Files looks something like:
FILE 1
Date, Time_1, Data_1
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
FILE 2
Date, Time_2, Data_2
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
I want them all with the same header, example:
Date, Time, Data
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
02032023, 24:25, 34234.4
How can I go about doing this?
댓글 수: 0
채택된 답변
Jack
2023년 3월 30일
You can use a loop to iterate through all the files, read them in, change the headers, and then save them with the updated headers. Here's an example code that should accomplish what you want:
% set the new headers you want to use
new_headers = {'Date', 'Time', 'Data'};
% specify the folder where your files are located
folder = 'path/to/your/folder/';
% get a list of all the files in the folder
files = dir(fullfile(folder, '*.txt'));
% loop through each file and update the headers
for i = 1:numel(files)
% read in the file
file_path = fullfile(folder, files(i).name);
file_data = readtable(file_path);
% update the headers
file_data.Properties.VariableNames = new_headers;
% save the updated file
writetable(file_data, file_path);
end
This code assumes that all your text files are in the same folder and have a .txt file extension. You may need to modify the dir function to match your specific file naming convention.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!