When importing a data file what are the comment symbols for Mathematica? That is, given a file like this
blabla
bulbul
1 2 6 54 7 ...
..
what symbol do I have to put in front of header lines so Mathematica skips them and starts reading at the line 1 2 6 54 7 ...
. I tried #
, which works in gnuplot, but that did not work.
I know that I could just tell Mathematica to skip the lines, but as I can control the file output, it would be nicer to use some kind of a tag.
Answer
Here is an approach that handles interspersed comments in addition to "headers"
FilePrint["test.txt"]
#comment
#comment
#comment
1 2 3
#c2
4 5 6
7 8 9
ImportString[
StringReplace[Import["test.txt", "Text"],
StartOfLine ~~ "#" ~~ Shortest[___] ~~ EndOfLine ~~ "\n" -> ""], "Table"]
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
of course you can invent whatever convention you want or even a mix, eg..
`StartOfLine ~~ {"#", "!", "%"} ~~ ...`
another variant:
ImportString[StringJoin@Riffle[
Select[StringSplit[Import["test.txt", "Text"], "\n"],
StringTake[#, 1] != "#" &], "\n"], "Table"]
Even handle end-of-line comments:
#comment
1 2 3
#c2
4 5 6 #note 1
7 8 9
ImportString[StringReplace[Import["test.txt", "Text"], {
StartOfLine ~~ "#" ~~ Shortest[___] ~~ EndOfLine ~~ "\n" -> "",
"#" ~~ Shortest[___] ~~ EndOfLine -> ""
}], "Table"]
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Tested on Windows by the way -- this might need some tweaking to handle different line endings on other systems
Comments
Post a Comment