MATLAB Answers

How to change a line in .txt file by importing a name, from a loop

1 view (last 30 days)
Ivan Michael
Ivan Michael on 4 Apr 2020
Hello,
I have a problem with a code. I would like to change a line in a .txt file . I would like the content of this line to be from an another .csv file (a 200x1 matrix file). by creating a loop I would like to change the content of a line for every line of the .csv file. My question is How could I make it. I mean How could I change the line , importing line by line the content of the .csv file. (I put an example of the .csv file)
I know that in order to change the content of a line I should use thw following commands:
filenameB = 'OLD_file';
outfilenameB = 'new_file';
LineToChange1 = 68;
NewContent1 = ' 6.4 30';
S = fileread(filenameB);
SS = regexp(S, '\r?\n', 'split');
SS{LineToChange1} = NewContent1;
fid = fopen(outfilenameB, 'w');
fprintf(fid, '%s\n', SS{:});
fclose(fid);

  6 Comments

Show 3 older comments
Andreas Bernatzky
Andreas Bernatzky on 5 Apr 2020
Hey Ivan,
thanks for the feedback and the file. So in the end there should be two files right?
File1: File 2:
This 10
is 20
a 30
text 40
for 50
showing 60
file 70
importing 80
For data with different types (string and integer) I would suggest you a table:
opts = detectImportOptions('test.csv');
opts.DataLines(1) = 1; %begin in first row
opts.DataLines(2) = Inf; %until fileEnd
T = readtable('test.csv',opts);
for(a = 1 : 1 : size(T,1))
% do something with your data
end
%use another write command if you are not processing cells
%writematrix or writetable depends on your application
writetable(T,'yourNewFile');
In table T you have something similiar to a 200x2
A table in matlab is pretty neat and easy to handle (better than cell-vectors in my opinion).
I might have the problem that I do not exactly know what your end result should be. But try my new code and look if it suits your application.
Ivan Michael
Ivan Michael on 5 Apr 2020
Hello Andreas Bernatzky. First of all thank you for your help. I have one last question. In the new file I have What I need, but to be honest I would like to delete the first line (Var1,Var2 in the output) and the delimiter "," between 2 columns in one line. I send you the final output that cames from your last version code and I hope you can solve my question please.
Thank you again !!!
dpb
dpb on 5 Apr 2020
That's completely different than the problem you described before of editing an existing file with the locations in the file being given by another along with the substitute text. Need to define what the problem really is...
writetable can avoid writing the variable names via 'WriteVariableNames',0 but it can't eliminate the delimiter. Every column in the table is a field.

Sign in to comment.

Answers (3)

dpb
dpb on 4 Apr 2020
Edited: dpb on 4 Apr 2020
OK, given a row and text to be in said row in the alternate file, that's pretty simply done--I'll also illustrate the newfangled strings class that's pretty handy---
s=splitlines(string(fileread('sonnets.txt'))); % read a sample file to mung on; make into strings
sss=s(1:100); % it's pretty long; just save first 100 lines to mung on
fid=fclose(fid); % done with that file...
fid=fopen('test.csv','r'); % read the row and text to use to edit with...
txtrow=textscan(fid,'%s%d','delimiter',','); % it's a string and an integer, comma-delimited
fid=fclose(fid); % done with it, too...
sss(txtrow{:,2})=string(txtrow{:,1}); % ok, make the substitution of the text in the row
>> sss(5:32) % print what's the new portion of the original contains
ans =
28×1 string array
""
""
""
" I"
""
"This "
" That thereby beauty's rose might never die,"
" But as the riper should by time decease,"
" His tender heir might bear his memory:"
" But thou, contracted to thine own bright eyes,"
" Feed'st thy light's flame with self-substantial fuel,"
" Making a famine where abundance lies,"
" Thy self thy foe, to thy sweet self too cruel:"
" Thou that art now the world's fresh ornament,"
" And only herald to the gaudy spring,"
"is"
" And tender churl mak'st waste in niggarding:"
" Pity the world, or else this glutton be,"
" To eat the world's due, by the grave and thee."
""
" II"
""
" When forty winters shall besiege thy brow,"
" And dig deep trenches in thy beauty's field,"
" Thy youth's proud livery so gazed on now,"
"a"
" Then being asked, where all thy beauty lies,"
" Where all the treasure of thy lusty days;"
>>
shows the text from the file stuck in the original...just write it back out and done.

  0 Comments

Sign in to comment.


dpb
dpb on 5 Apr 2020
OK, not knowing which is the anwer really wanted but apparently from above comment just concatenating the two columns in the table and outputting them is all that is wanted...using both approaches something like:
txtrow=readtable('text.csv'); % use the table route to read the file
txtrow.Var1=string(txtrow.Var1); % convert to string from cellstr first
newtxt=txtrow.Var1+txtrow.Var2; % use magic conversion of string + operator to convert numbers
writematrix(newtxt,'yourNewFile.txt') % and write a text file

  0 Comments

Sign in to comment.


Andreas Bernatzky
Andreas Bernatzky on 6 Apr 2020
should finally do the work now:
opts = detectImportOptions('test.csv');
opts.DataLines(1) = 1; %begin in first row
opts.DataLines(2) = Inf; %until fileEnd
T = readtable('test.csv',opts);
for(a = 1 : 1 : size(T,1))
% do something with your data
end
%use another write command if you are not processing cells
%writematrix or writetable depends on your application
writetable(T,'yourNewFile','Delimiter',' ','WriteVariableNames',0);

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by