如何从txt文件中提取数据并将其重命名为较小的文件

时间:2016-02-24 16:19:12

标签: matlab text-files

有谁知道如何从txt文件中提取数据。我的文本文件有3列,我基本上试图提取前30行并将其保存为不同的txt文件。然后是下一个30,依此类推,直到我离开了多个较小的文本文件,每个文件包含30行数据。

1 个答案:

答案 0 :(得分:1)

您可以使用fgets检索输入的每一行,并fprintf将输出写入新文件。它真的不关心你有多少列数据。它将全部保留。

lines_per_file = 30;

% Load the source file
fin = fopen('input.txt', 'r');

% Retrieve the first line
line = fgets(fin);

% Keep track of how many lines are in the current file
nLines = 0;
nFiles = 1;

% Loop until we have read all lines
while line ~= -1

    % Check to see if we need to start a new file
    if mod(nLines, lines_per_file) == 0
        % Close the old file if it's open and exists
        if exist('fout', 'var'); fclose(fout); end

        % Open the output file of the format output.XX.txt
        fout = fopen(sprintf('output_%d.txt', nFiles), 'w');
        nFiles = nFiles + 1;
    end

    % Write the line to the output
    fprintf(fout, line);

    % Retrieve the next line
    line = fgets(fin);
    nLines = nLines + 1;
end

% Clean up file identifiers.
fclose(fout);
fclose(fin);

这将获取输入文件(' input.txt')并创建以下格式的N个输出文件:

output_1.txt
output_2.txt
...
output_N.txt