I have a CSV file with key-value pairs, and I want to be able to read the file into latex, and generate macros to access the values. Here is my current attempt with datatool
:
\documentclass{article}
\usepackage{datatool,filecontents}
\newcommand{\loadmap}[2][map]{%
\DTLloaddb{#1}{#2}%
\DTLforeach{#1}{\Key=Key,\Value=Value}{%
\expandafter\def\csname #1\Key\endcsname{\Value}}}
\newcommand{\loadmaptest}[2][map]{%
\DTLloaddb{#1}{#2}%
\DTLforeach{#1}{\Key=Key,\Value=Value}{\Key,\Value\\}}
\begin{document}
\begin{filecontents}{testdata.csv}
Key,Value
firstkey,0.002
secondkey,1.0
thirdkey,4
\end{filecontents}
\loadmap{testdata.csv}
\mapfirstkey,\mapsecondkey,\mapthirdkey\\
\loadmaptest[second]{testdata.csv}
\end{document}
You will see that the output is something like:
4,4,4
firstkey,0.002
secondkey,1.0
thirdkey,4
So, while the DTLforeach
is correctly iterating through the CSV file when directly displaying the results, the generation of the macros is incorrect. In particular, it correctly generates the macro names as \mapfirstkey
, etc. but the value for all of them is the last value in the keys. I suspect this has something to do with me incorrectly expanding macros...
Any ideas?
\edef
instead\def
.\edef
accept numbers?\expandafter\edef\csname macro123\endcsname{definition}
, or am I missing the point of your question?