Appending a Path to a Path
<p>Is it possible to append a <code>pathlib.Path</code> generator or, combine two <code>Path</code>s?</p>

<pre><code>from pathlib import Path
paths = Path('folder_with_pdfs').glob('**/*.pdf')
paths.append(Path('folder_with_xlss').glob('**/*.xls'))
</code></pre>

<p>With this attempt you'll get:</p>

<pre><code>AttributeError: 'generator' object has no attribute 'append'
</code></pre>

<p>That's because <a href="https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob" rel="nofollow"><code>Path.glob</code></a> returns a <code>generator</code>, i.e an object that returns values when <code>next</code> is called which has absolutely no idea what <code>append</code>ing is.</p>

<p>You have two options here, if you require a list wrap the paths in a <code>list</code> call:</p>

<pre><code>paths = list(Path('folder_with_pdfs').glob('**/*.pdf'))
paths.append(list(Path('folder_with_xlss').glob('**/*.xls')))
</code></pre>

<p><sub>(Even though <code>extend</code> is probably what you're after here.)</sub></p>

<p>this of course defeats the purpose of the generator. </p>

<p>So, I'd suggest using something like <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> and creating a generator that will combine them and yield from them one at a time:</p>

<pre><code>from itertools import chain

p1 = Path('folder_with_pdfs').glob('**/*.pdf')
p2 = Path('folder_with_xlss').glob('**/*.xls')
paths = chain(p1, p2)
</code></pre>

<p>Then iterating over <code>paths</code> as required while keeping the memory footprint down.</p>

python python-3.x pathlib