How to write to an existing column of a file?

조회 수: 3 (최근 30일)
Kash Costello
Kash Costello 2018년 10월 29일
편집: per isakson 2018년 11월 1일
Hey there,
I have a .daf file here (you can open in wordpad) and you can see that there are 10 columns. I want to overwrite just the sixth column with number 1 (they're all 0's but in some rows I want to put 1). Like say on the 100th, 200th, 300th rows, I want to make them 1. I also want to save it in the same file.
How can I do that? Can someone help me?
Thank you!

답변 (1개)

per isakson
per isakson 2018년 10월 29일
편집: per isakson 2018년 11월 1일
AJ739_20170127115441_v2.daf is an UTF-8 encoded text file according to Notepad++.
It's close to impossible to overwrite a column in a text file.
You have to read the file and write a new file (or overwrite the old) with modified data.
In response to comments
There are many ways. This outlines a simple one.
fid_in = fopen( 'AJ739_20170127115441_v2.daf', 'r' );
fid_out = fopen( 'any_name_and_remane_later.txt', 'w+' );
str = 'anything';
while not( strcmp( str, '"***Data start***"' ) )
str = fgetl( fid_in );
fprintf( fid_out, '%s\n', str );
end
cac = textscan( fid_in, '%d...%q', 'Delimiter',',' )
fclose( fid_in )
...
fclose( fid_out )
Read about UTF-8 in the help on fopen
I'm not sure I understand "I want to overwrite just the sixth column with number 1 (they're all 0's but in some rows I want to put 1). Like say on the 100th, 200th, 300th rows, I want to make them 1." The sixth column of the uploaded file contains only zeros.
The code below writes a modified file with tab-delimited data.
fid_in = fopen( 'AJ739_20170127115441_v2.daf', 'r' );
fid_out = fopen( 'any_name_and_remane_later.txt', 'w+' );
str = 'anything';
while not( strcmp( str, '"***Data start***"' ) )
str = fgetl( fid_in );
fprintf( fid_out, '%s\n', str );
end
0,0,0,0,0,0,0,0,0,"(0)[0.00/ 0]" 252502,49,1,0,0,0,0,0,0,"Respiratory Level Error.(0)[1.87/ 488]"
cac = textscan( fid_in, '%d%d%d%d%d%d%d%d%d%q' ...
, 'Delimiter',',', 'CollectOutput',true );
fclose( fid_in );
my_data = cac{1};
str = cac{2};
The 6th column contains only zeros; all(my_data(:,6)==0) returns true
my_data(:,6) = 1;
for jj = 1 : size(my_data,1)
fprintf( fid_out, '%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t"%s"\n' ...
, my_data(jj,:), str{jj} );
end
fclose( fid_out );
disp('Done!')
  댓글 수: 3
per isakson
per isakson 2018년 10월 31일
See addendum in my answer.
Kash Costello
Kash Costello 2018년 10월 31일
I saw! Thanks! What about writing the 10 columns below the string characters? I've been trying to figure that out but I don't know how to write them >.<

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

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by