필터 지우기
필터 지우기

CSV: Create New Headerline

조회 수: 5 (최근 30일)
Amanda
Amanda 2013년 5월 6일
In a CSV file, I would like to replace (delete) a headerline, first line, and create a new headerline. So the CSV file is (for this example I applied extra spaces to make it more readable):
State, Tornado, Hurricane, Earthquake,
Texas, 34, 5, 0,
Indiana, 8, 0, 2,
California, 2, 2, 20,
North Carolina, 1, 10, 1,
So now I need to delete the first headerline and replace it with a new headerline -- ST TOR HUR EAR -- see below:
ST, TOR, HUR, EAR,
Texas, 34, 5, 0,
Indiana, 8, 0, 2,
California, 2, 2, 20,
North Carolina, 1, 10, 1,
Thanks,
Amanda
  댓글 수: 2
Cedric
Cedric 2013년 5월 6일
I still don't know whether there are commas in your CSV file or if the content is really like what is written in your question (?)
Amanda
Amanda 2013년 5월 6일
편집: Amanda 2013년 5월 6일
Yes -- there are commas. I will edit it.

댓글을 달려면 로그인하십시오.

채택된 답변

Cedric
Cedric 2013년 5월 6일
편집: Cedric 2013년 5월 6일
Assuming that there is no comma but tabs ( \t ) as delimiters, I give you one way to do it:
% - Read input file data content (without header).
fid_in = fopen('myFile.csv', 'r') ; % Open input file for reading.
fgetl(fid_in) ; % Skip header line in input file.
content = fread(fid_in) ; % Read rest of input file.
fclose(fid_in) ; % Close input file.
% - Write output file: new header + previous data content.
fid_out = fopen('myFile_newHeader.csv', 'w') ; % Open input file for writing.
fprintf(fid_out, 'ST\tTOR\tHUR\tEAR\n') ; % Output new header.
fwrite(fid_out, content) ; % Output previous data content.
fclose(fid_out) ; % Close output file.
  댓글 수: 2
Amanda
Amanda 2013년 5월 6일
WOW! Thanks. You have been one of the most helpful forum members. And most of all, I am learning so much.
Cedric
Cedric 2013년 5월 6일
You're welcome, I'm glad it helps!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by