【问题标题】:read csv file with mixed end of line读取带有混合行尾的csv文件
【发布时间】:2015-06-04 20:30:22
【问题描述】:

我有一个混合行结尾的 '\n' 和 '\r\n' 的 csv 文件。使用 csvread 时,csvread 会报错,而使用 textscan 时,textscan 只会扫描行结束字符变化前的内容。 如何在 matlab 中输入此文件而不对文件进行预处理以修复行尾?

示例文件:

 fid = fopen('ex1.csv', 'w');
 fprintf(fid, 'A,B,C\n');
fprintf(fid, '1,1,1\n');
 fprintf(fid, '2,2,2\r\n');
fprintf(fid, '3,3,3\r\n');
fclose(fid);

注意标题限制了load的使用,importdata会漏掉最后一行。

【问题讨论】:

  • 如果只是标题有问题,那么可以在行首放一个%。然后 MATLAB 会将其视为注释,load 将起作用。
  • @JeffIrwin 或者,只需在 Matlab 编辑器中打开文件并将其保存回来;它会自动转换为正确的 EOL(至少在 Windows 上)。

标签: matlab csv file-io


【解决方案1】:

更新

使用新的示例输入,我可以确认没有任何内置方法可以正常工作。这是使用textscanreshape 的解决方案:

fid = fopen('ex1.csv');
inputMatrix = textscan(fid, '%s', 'delimiter', ',');
fclose(fid);
inputMatrix = reshape(a{1}, 3, [])';    %'//assuming 3 columns in file

>> inputMatrix 
    'A'    'B'    'C'       
    '1'    '1'    '1'       
    '2'    '2'    [1x2 char]    %//the 2nd char is "\r"
    '3'    '3'    [1x2 char]

或者,当方便的功能不起作用时,我通常只是恢复到老式的文件读取方式:

fid = fopen('ex1.csv');
inputMatrix = {};
while ~feof(fid)
    line = fgetl(fid);
    inputMatrix(end+1,:) = strsplit(line, ',');
end
fclose(fid);

>> inputMatrix
inputMatrix = 
    'A'    'B'    'C'
    '1'    '1'    '1'
    '2'    '2'    '2'
    '3'    '3'    '3'

注意,这样做的好处是不关心有多少列,而且也不包括\r

在任何情况下,您可能希望数字是数字矩阵而不是字符串的单元矩阵。对str2double 的简单调用将为您完成此操作(它会巧妙地忽略任何\r):

str2double(inputMatrix(2:end,:))

上一个

如果没有示例文件,我只能根据我在本地创建的简单输入提出建议,在我看来,importdataload 都可以工作,具体取决于您输入数据的结构。

示例输入 1:

>> fid = fopen('ex1.csv', 'w');
>> fprintf(fid, '1,1,1\n');
>> fprintf(fid, '2,2,2\r\n');
>> fprintf(fid, '3,3,3\n');
>> fclose(fid);

>> a = importdata('ex1.csv')
ans = 
     1     1     1
     2     2     2
     3     3     3
>> a = load('ex1.csv')
ans = 
     1     1     1
     2     2     2
     3     3     3

示例输入 2:

>> fid = fopen('ex2.csv', 'w');
>> fprintf(fid, '1,1,1\n');
>> fprintf(fid, '2,2,2\r\n');
>> fprintf(fid, '3,3\n');
>> fclose(fid);

>> a = importdata('ex2.csv')
ans = 
     1     1     1
     2     2     2
     3     3     NaN
>> a = load('ex2.csv')
Error using load
Number of columns on line 3 of ASCII file ex2.csv must be the same as previous lines. 

【讨论】:

    【解决方案2】:

    我结束了

    fid = fopen('ex1.csv');
    inputMatrix = cell2mat(textscan(fid, '%f%f%f%*[^\n]', 'delimiter', ',','headerLines',1));
    fclose(fid);
    
    
    >> inputMatrix
    
    inputMatrix =
    
         1     1     1
         2     2     2
         3     3     3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2015-12-11
      • 1970-01-01
      相关资源
      最近更新 更多