Is there a way to include all files in a directory and all sub directories in a report as a code appendix using the listings package?

I know I can include each individual file using the listings package and \lstinputlisting, but I'm just wondering whether there is a quicker way to insert them in a code appendix...

  • 1
    There are at least two ways to automate this kind of problem. If you are using LuaLaTeX you could insert a piece of Lua script directly in your tex file to scan a folder and write those files to your tex file. Otherwise you could also use a shell script to construct a separate tex file with all the listings, and input that in your main tex file. In both cases some tweaking is necessary depending on the operating system you use (windows, linux, mac).
    – hugovdberg
    Mar 19, 2014 at 8:47
  • Also related: tex.stackexchange.com/questions/6547/…
    – jub0bs
    Mar 19, 2014 at 13:00
  • Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count (see How do you accept an answer?). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers.
    – jub0bs
    Apr 8, 2014 at 18:21
  • I ended up using a shell script to build a file with each file and a blank caption for the file. I would mark @hugovdbergs comment as accepted if an answer. May 2, 2014 at 17:05

2 Answers 2


A good solution that also works for listings was provided here: How to iterate through the name of files in a folder. You just have to modify the code like this:


  \app@exe{ls #1/* | xargs cat >> \jobname.tmp}%
  \AtEndDocument{\app@exe{rm -f #1/\jobname.tmp}}}




Note that, if you are running under windows, you will have to replace \app@exe commands by something like (not tested, but based on the answer given in the previous thread):

\app@exe{cmd /c dir /b * > \jobname.tmp}%
\AtEndOfDocument{\app@exe{rm -f #1/\jobname.tmp}}}

The code I gave will include all the files of the directory. If you want to only include files with a given extension you can specify it directly in \app@exe command.

Don't forget to compile using pdflatex -shell-escape yourfile.tex.


I was trying to use this to load python code. However, your example only listed the names of the files. Was that the intention? Anyway, the following seems to work for me. Is there a more elegent way?

\usemintedstyle{friendly} % Python Code Style

  \app@exe{cmd /c dir /b *.py > \jobname.dat}%
    \AtEndDocument{\app@exe{cmd rm -f #1/\jobname.dat}}}


\createData{.}% from the current dir 

\foreach \i in {0,...,\rows} {
        \subsection*{Source code for \textsf{\pgfplotsretval}}


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .