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

조회 수: 1 (최근 30일)
Ivan Mich
Ivan Mich 2020년 4월 4일
답변: Andreas Bernatzky 2020년 4월 6일
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
Ivan Mich
Ivan Mich 2020년 4월 5일
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 2020년 4월 5일
편집: dpb 2020년 4월 5일
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.

댓글을 달려면 로그인하십시오.

답변 (3개)

dpb
dpb 2020년 4월 4일
편집: dpb 2020년 4월 4일
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.

dpb
dpb 2020년 4월 5일
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

Andreas Bernatzky
Andreas Bernatzky 2020년 4월 6일
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);

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by