Clear Filters
Clear Filters

Change file header and save the file -- do this for all files in directory.

16 views (last 30 days)
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?

Accepted Answer

Jack
Jack on 30 Mar 2023
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.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!