Q:

Python code in LaTeX not running

The Latex/Python Project:
Create in Latex a songbook from pdf files in a folder and make a toc.
Problem:
The code below is not running in Latex. Thanks to G.Poore I added the \verb command to overcome problems with underscores etc. Still, it doesnt work. I think the problems are:

Latex is somehow removing the indentation
There might be still some other coding mistakes which I cant test because of 1. (sorry...)

usepackage python vs pythontex:
I am using python because

Its easier just to run one file than latex/python/latex 
for some reasons pythontex is not running on my mac, but no problem, see 1.

Can anybody give me some hints? Thanks!
  % !TEX program = XeLaTeX+shell-escape
\documentclass{article}
\usepackage{hyperref}
\usepackage{python}
\usepackage[final]{pdfpages}
\usepackage[ngerman]{babel}

\begin{document}
\begin{python}
import os
from Tkinter import Tk
from tkFileDialog import askdirectory

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing

# show an "Open" dialog box and return the path to the selected file
Liederpfad = askdirectory(title="Choose folder:") 

# get filenames from path
v5 = os.listdir(Liederpfad)

# remove "symlink" if there
for name in v5:
    if name.endswith("symlink"):
        os.rename(Liederpfad + "/" + name, Liederpfad + "/" + name[:-8])

# write latex code
for x in v5:
    if not x.startswith("."): #versteckte Systemdateien ausblenden
        print ('\\phantomsection')
        if x.endswith("symlink"):
            print ('\\addcontentsline{toc}{section}{\\verb|' + x[:-12] + '|}\n')
        else:
            print ('\\addcontentsline{toc}{section}{\\verb|' + x[:-4] + '|}\n')
        print ('\\includepdf[fitpaper=true,pages=-,pagecommand={\\thispagestyle{fancy}}]{\\verb|' + Liederpfad + '/' + x + '|}\n)
        print ('')
\end{python}

\tableofcontents
\end{document}

A:

In your short example, you are trying to print file names.  But in general, file names will not be valid LaTeX, since they may contain underscores, etc.  If you do something like
print('\\verb|' + name + '|\n')

then the file names will be wrapped in a \verb command and thus special characters won't be an issue.
Also, you don't need the % after the python environment.
Depending on what you ultimately want to do, you may wish to consider the pythontex package.  It provides a lot of additional features, but also involves a three-step compile process (LaTeX, pythontex.py, and then LaTeX again)

