How to write to an existing column of a file?
1 view (last 30 days)
Show older comments
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!
0 Comments
Answers (1)
per isakson
on 29 Oct 2018
Edited: per isakson
on 1 Nov 2018
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 Comments
See Also
Categories
Find more on Text Files 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!