[Tex/LaTex] Read strings from file that contains the special character #

catcodesfilesystem-accessmacros

I need to read some values from data files as given in the sample code.
The problem arises when the files contain # character.
Then I get " ! Illegal parameter number in definition of \@xs@call " error.

The point is the files are generated by another program and there are bunch of them that makes it difficult to simply change the files by hand.

Any ideas how to deal this issue?

\documentclass{article}
\usepackage{xstring}
\usepackage{filecontents}

% WORKS FINE !!!
\begin{filecontents*}{myfile1.txt}
mean: 0.26068087303584447 lablab
\end{filecontents*}

% if in my file there are special characters (e.g #) then I get errors :( !!!
\begin{filecontents*}{myfile2.txt}
# mean: 0.26068087303584447 lablab
\end{filecontents*}

\newread\myread  
\newcommand{\readmean}[1]{
  \openin\myread=#1
  \read\myread to \mystr
  \StrBetween{\mystr}{mean: }{ lablab}[\mymean]
  \closein\myread
}

\begin{document}

\readmean{myfile1.txt}
mean1 : \mymean

\readmean{myfile2.txt}
mean2 : \mymean

\end{document}

UPDATE

Here is part of an example input file:

 # created by PartHist. 
 # range: 0.0 - 1.0
 # mPDF info : 
 # mean: 0.10367941480330108 std:0.081293127812218507
 # args: (1.3542643666732745, 11.707772771967631)
 #
 x y
 0.02 6.47
 0.04 3.21
 .
 .
 .

Actually I plot the data and I would like to put the additional information like mean and std on the plot which is given in the header file.

Best Answer

If you want only the file myfile2.txt to be readable, the solution may be as follows:

\documentclass{article}
\usepackage{xstring}
\usepackage{filecontents}

% WORKS FINE !!!
\begin{filecontents*}{myfile1.txt}
mean: 0.26068087303584447 lablab
\end{filecontents*}

% if in my file there are special characters (e.g #) then I get errors :( !!!
\begin{filecontents*}{myfile2.txt}
# mean: 0.26068087303584447 lablab
\end{filecontents*}

\newread\myread  
\newcommand{\readmean}[1]{
  \openin\myread=#1
  \read\myread to \mystr
  \StrBetween{\mystr}{mean: }{ lablab}[\mymean]
  \closein\myread
}

\begin{document}

\readmean{myfile1.txt}
mean1 : \mymean

{\catcode`\#=11
\readmean{myfile2.txt}
mean2 : \mymean
}


\end{document}

enter image description here

Related Question