[英]How do I write to a text file in MATLAB?
我需要从index.html文件的每一行中删除'index.html'字符串。...
我需要在MATLAB中完成此操作。
这是我到目前为止所拥有的...
修改后,我不知道如何编写该行,并重新回到html文件中的同一行。
fid=fopen('index.html');
while ~feof(fid)
tline=fgetl(fid);
if ~isempty(strfind(tline,'index.html'))
remline=strrep( tline ,'index.html','');
**% fprintf(fid,remline);
% fprintf('\n')**
end
end
此解决方案为我工作:
function WriteToFile(filename)
fid = fopen(filename, 'r+');
fid2 = fopen('index.txt', 'w');
while ~feof(fid)
tline=fgetl(fid);
if ~isempty(strfind(tline,'index.html'))
remline=strrep(tline,'index.html','');
fprintf(fid2, '%s\r\n', remline);
else
fprintf(fid2, '%s\r\n', tline);
end
end
fclose(fid);
fclose(fid2);
delete(filename)
keyboard
movefile('index.txt','index.html')
将%d替换为%s以获取实际文本
这是一个示例函数:
function WriteToFile(filename, text)
%open file with write permission
fid = fopen(filename, 'w');
%write a line of text
fprintf(fid, '%d\n', text);
%close file
fclose(fid);
如果您使用的是文本文件,那么研究文档的文件fileread
和textscan
功能将非常有用。 您所采用的方法没有什么问题(除了显而易见的事情,即您尚未使它工作),但这比所需的要麻烦得多。
我希望,如果您将文件读入Matlab字符串(允许空间限制),然后对其运行正则表达式,则可能可以一次替换掉。
您对fopen()
调用将打开该文件以供只读,这就是为什么fprintf()
调用失败的原因。 但是,这种方法无法按原样工作,因为您正在更改文本行的长度。 我建议您从输入文件中读取每一行,进行更改,然后将其写到临时输出文件中。 处理完每个输入行后,请关闭两个文件,删除输入文件,然后将临时输出文件重命名为原始输入文件名。
或者,如HPM所建议的那样,将整个文件一次性读取到内存中,处理每一行,然后一次全部写入“输入”输入文件的顶部。
修改Niko的答案(将%d替换为%s)以将实际文本放入文件a1.m中:
fid = fopen('a1.m','w');%open file for writing
fprintf(fid, '%s\n', 'some_text');%write a line of text
fclose(fid);%close file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.