Azzera filtri
Azzera filtri

How to put a header in a txt file?

17 visualizzazioni (ultimi 30 giorni)
Bruno Souza
Bruno Souza il 20 Feb 2018
Commentato: shobhit pipil il 6 Feb 2019
I'd like to put a header in my .txt file. I have a file with 744 lines like below. And I wanna put on the first line the header 'hora'.
001
002
003
004
005
006
...
744

Risposta accettata

Akira Agata
Akira Agata il 21 Feb 2018
Straight-forward solution would be like this:
% Read the file
fid = fopen('yourData.txt','r');
str = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
% Add your header
str2 = [{'hola!'}; str{1}];
% Save as a text file
fid2 = fopen('output.txt','w');
fprintf(fid2,'%s\n', str2{:});
fclose(fid2);
  6 Commenti
Akira Agata
Akira Agata il 5 Feb 2019
Hi Shobhit-san,
Sorry, I don't catch your concern correctly.
Do you want to add a header in a txt data file (as described in the original question)?
Or, do you want to read txt data file as a numeric array?
Anyway, I believe the following slightly modified code can do both of them. I hope this will be some help to address your problem!
fileList = dir('Input/*.txt');
for kk = 1:numel(fileList)
% Read the file
fid = fopen(['Input/',fileList(kk).name],'r');
str = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
% Convert data into numeric matrix
data = str2double(str{1});
% ----------------------------------------------------
% Do something by your model which takes data as float
% ----------------------------------------------------
% Add your header
str2 = [{'hola!'}; str{1}];
% Save as a text file
fid2 = fopen(['Output/',fileList(kk).name],'w');
fprintf(fid2,'%s\n', str2{:});
fclose(fid2);
end

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by