How to write to an existing column of a file?

3 次查看(过去 30 天)
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 个评论
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 中查找有关 Large Files and Big Data 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by