# How to Insert into Latex a Text File whose name is a variable?

I need to insert a text file into LaTeX. But text file names are different for different projects. So I want to define text file name as a variable and refer to the variable when inserting the text

I tried the code as below. But

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{{\myfile}}


doesn't work. Only

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{abc.txt}


Could anyone give me some guide?

\usepackage{fancyvrb}
<<text, echo=F>>=
targetvar<-'abc'
textfile<-paste(targetvar,'.txt',sep='')
@
\newcommand{\myfile}{\Sexpr{textfile}}
\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{{\myfile}}

-

## migrated from stackoverflow.comMay 10 '12 at 21:02

This question came from our site for professional and enthusiast programmers.

@Werner -- I disagree in this case. The questioner wants to know how to use a file name calculated in R to insert text file into the *.tex file that will then be compiled by LaTeX. –  Josh O'Brien May 10 '12 at 20:53
Welcome to TeX.sx! Your question was migrated here from Stack Overflow. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question. –  Werner May 10 '12 at 21:05
You use {{\myfile}} - why do you take 2 {? Can you try \VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{\myfile} –  knut May 10 '12 at 21:19

You can use Sweave's results=tex code chunk argument to construct a LaTeX \input{} directive that will insert the text from whatever file path R constructed.

This Sweave file (call it "example.Rnw") ...

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

<<text, echo=FALSE, results=tex>>=
targetvar<-'abc'
textfile <- paste(targetvar,'.txt',sep='')

cat("\\VerbatimInput[baselinestretch=1,fontsize=\\footnotesize]{",
textfile,
"}", sep="")
cat("\n")
@

\end{document}


... will produce this LaTex file ("example.tex") after being run through Sweave by a call to Sweave("example.Rnw"):

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{abc.txt}

\end{document}

-

Can you try \VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{\myfile}

This MWE works:

\documentclass{article}
\usepackage{fancyvrb}

\newcommand{\myfile}{\jobname}

\begin{document}
\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{\myfile}

\end{document}


Background: You use {{\myfile}} - If \myfile is test.txt, then the filename to load is {test.txt} - including the braces. Without the additional braces, it works fine.

-