简体   繁体   English

MATLAB:向 csv 文件添加新行

[英]MATLAB: add a new row to csv file

Pretty straightforward in theory, but ridiculously complex in practice?理论上很简单,但在实践中却非常复杂? Or I am missing something obvious?还是我遗漏了一些明显的东西?

I import my file file.csv .我导入我的文件file.csv It is simply 10 empty columns named col1 to col10 (0x10 empty table)它只是名为 col1 到 col10 的 10 个空列(0x10 空表)

file = readtable('~/.../file.csv');

Here is the new row I want to add to this file这是我要添加到此文件的新行

newline = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'};

Now I want to add this row to file and write it back to csv.现在我想将此行添加到文件中并将其写回 csv。

Solution 1 I have tried解决方案1我试过

Add the line with添加行

file = [file; newline];

Then write file to csv, with:然后将文件写入 csv,其中:

csvwrite('~/.../out.csv',file);

Nope.没有。

Error using csvwrite (line 47) Undefined function 'real' for input arguments of type 'table'.使用 csvwrite 时出错(第 47 行)未定义 function 'real' 用于类型“表”的输入 arguments。

Or perhaps也许

writetable('~/Dropbox/phd/sleepAnalysis/database/out.csv',file);

Nope.没有。

Error using writetable (line 124) Input must be a row vector of characters or string scalar.使用 writetable 时出错(第 124 行) 输入必须是字符的行向量或字符串标量。

Solution 2 I have tried解决方案2我试过

Just add the new line while writing the file只需在写入文件时添加新行

dlmwrite('~/.../out.csv',newline,'-append','delimiter',',');

It does write the file, but it adds one column per character to the left.它确实写入了文件,但它在左侧每个字符添加一列。 Obviously not what I am (or anyone really) after here.显然不是我(或任何人)在这里之后。

How it looks:它的外观: 在此处输入图像描述

Can't possibly be this hard?不可能这么难吧? Can you help?你能帮我吗?

"writetable" is the right solution. “可写”是正确的解决方案。 You just need to put the table first and the file name second.您只需要将表格放在第一位,然后将文件名放在第二位。

    file = table([],[],[],[],[],[],[],[],[],[],'VariableNames',{'col1','col2','col3','col4','col5','col6','col7','col8','col9','col10'})
    newline = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'};
    file = [file ; newline]
    writetable(file,'out.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM