remove character from csv file header

6 ビュー (過去 30 日間)
John
John 2018 年 9 月 28 日
コメント済み: Walter Roberson 2018 年 10 月 2 日
How can a file be opened, then remove a character and save the file?
The attached csv file , test.csv, contains the following data:
a,b,c,
1,2,3
4,5,6
7,8,9
I need to remove the comma at the end of the header in order to properly read column variable names using readtable().

採用された回答

Walter Roberson
Walter Roberson 2018 年 9 月 28 日
You do not need to do that. There some other approaches you can take:
1) readtable() the file as-is. In R2018b at least, that will return a table with 3 variables named Var1, Var2, Var3 -- the original header will be gone . If you need to, you can assign the names to the Properties.VariableNames property of the table
2) Similar to the above, but you also
T = readtable('test.csv');
fid = fopen('test.csv', 'rt');
S = fgetl(fid);
fclose(fid);
varnames = regexp(S, ',', 'split);
varnames( cellfun(@isempty, varnames) ) = []; %remove any trailing empty fields
T.Properties.VariableNames = matlab.lang.makeUniqueStrings(matlab.lang.makeValidName(varnames));
3) Use textscan() to read the file, either with or without bothering to extract the variable names
4) If you do not need the variable names,
csvread('test.csv', 1, 0)
The 1 tells it to skip 1 row; the 0 tells it to skip zero columns.
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 10 月 2 日
There is another option for R2016b or later:
filename = 'test.csv';
opt = detectImportOptions(filename);
opt.VariableDescriptionsLine = 1;
data = readtable(filename, opt);
data.Properties.VariableNames = matlab.lang.makeUniqueStrings(matlab.lang.makeValidName(data.Properties.VariableDescriptions));
Grotty, but functional.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by