在matlab中打开文本文件,然后从matlab中保存它们 [英] Open text files in matlab and save them from matlab

查看:130
本文介绍了在matlab中打开文本文件,然后从matlab中保存它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大文本文件,其中包含需要提取并插入到新文本文件中的数据.我可能需要将此数据存储在单元格/矩阵数组中?

I have a big text file containing data that needs to be extracted and inserted into a new text file. I possibly need to store this data in an cell/matrix array ?

但是,现在的问题是,我正在尝试测试一个较小的数据集,以检查下面的代码是否有效.

But for now, the question is that I am trying to test a smaller dataset, to check if the code below works.

我有一个代码,其中将打开一个文本文件,对其进行扫描并复制数据,然后将其保存在另一个名为"output.txt"的文本文件中.

I have a code in which it opens a text file, scans through it and replicates the data and saves it in another text file called, "output.txt".

问题:似乎无法正确保存文件.它只是在文本文件中显示一个空数组,例如" [] ".原始文本文件仅包含字符串.

Problem : It doesn't seem to save the file properly. It just shows an empty array in the text file, such as this " [] ". The original text file just contains string of characters.

%opens the text file and checks it line by line.
fid1 = fopen('sample.txt');
tline = fgetl(fid1);
while ischar(tline)
    disp(tline);
    tline = fgetl(fid1);
end
fclose(fid1);


% save the sample.txt file to a new text fie
fid = fopen('output.txt', 'w');
fprintf(fid, '%s %s\n', fid1);
fclose(fid);

% view the contents of the file
type exp.txt

我从这里去哪里?

推荐答案

将输入文件的所有内容一次加载到内存中来读取输入文件不是一个好习惯.这样,您能够读取的文件大小受到计算机上内存量(或操作系统愿意分配给单个进程的内存量)的限制.

It's not a good practice to read an input file by loading all of its contents to memory at once. This way the file size you're able to read is limited by the amount of memory on the machine (or by the amount of memory the OS is willing to allocate to a single process).

相反,请使用fopen及其相关功能来逐行或逐字符读取文件.

Instead, use fopen and its related function in order to read the file line-by-line or char-by- char.

例如

fid1 = fopen('sample.txt', 'r');
fid = fopen('output.txt', 'w');

tline = fgetl(fid1);
while ischar(tline)
    fprintf(fid, '%s\n', tline);
    tline = fgetl(fid1);    
end

fclose(fid1);
fclose(fid);

type output.txt

当然,如果您事先知道输入文件永远不会很大,则可以使用textread或某些等效功能一次读取所有文件.

Of course, if you know in advance that the input file is never going to be large, you can read it all at once using by textread or some equivalent function.

这篇关于在matlab中打开文本文件,然后从matlab中保存它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆