title: How to move and rename documents placed in several nested folders into a new single folder with python?
body: <p>I have several files across several folders like this:</p>
  
  <pre><code>dir
  ├── 0
  │   ├── 103425.xml
  │   ├── 105340.xml
  │   ├── 109454.xml
  │
  │── 1247
  │   └── doc.xml
  ├── 14568
  │   └── doc.xml
  ├── 1659
  │   └── doc.xml
  ├── 10450
  │   └── doc.xml
  ├── 10351
  │   └── doc.xml
  </code></pre>
  
  <p>How can I extract all the documents into a single folder appending the folder name for each moved document:</p>
  
  <pre><code>new_dir
  ├── 0_103425.xml
  ├── 0_105340.xml
  ├── 0_109454.xml
  ├── 1247_doc.xml
  ├── 14568_doc.xml
  ├── 1659_doc.xml
  ├── 10450_doc.xml
  ├── 10351_doc.xml
  </code></pre>
  
  <p>I tried to extract them with:</p>
  
  <pre><code>import os
  
  for path, subdirs, files in os.walk('../dir/'):
      for name in files:
          print(os.path.join(path, name))
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Also, I tried to:</p>
  
  <pre><code>import os, shutil
  from glob import glob
  
  files = []
  start_dir = os.getcwd()
  pattern   = "*.xml"
  
  for dir,_,_ in os.walk('../dir/'):
      files.extend(glob(os.path.join(dir,pattern))) 
  for f in files:
      print(f)
      shutil.move(f, '../dir/')
  </code></pre>
  
  <p>The above gave me the path of each file. However, I do not understand how to rename and move them:</p>
  
  <pre><code>---------------------------------------------------------------------------
  Error                                     Traceback (most recent call last)
  &lt;ipython-input-50-229e4256f1f3&gt; in &lt;module&gt;()
       10 for f in files:
       11     print(f)
  ---&gt; 12     shutil.move(f, '../dir/')
  
  /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py in move(src, dst, copy_function)
      540         real_dst = os.path.join(dst, _basename(src))
      541         if os.path.exists(real_dst):
  --&gt; 542             raise Error("Destination path '%s' already exists" % real_dst)
      543     try:
      544         os.rename(src, real_dst)
  
  Error: Destination path '../data/230948.xml' already exists
  </code></pre>
  
  <p>The above error shows why I would like to rename it with its folder.</p>