title: How to insert a directory in the middle of a file path in Python?
body: <p>I want to insert a directory name in the middle of a given file path, like this:</p>
  
  <pre><code>directory_name = 'new_dir'
  file_path0 = 'dir1/dir2/dir3/dir4/file.txt'
  file_path1 = some_func(file_path0, directory_name, position=2)
  print(file_path1)
  &gt;&gt;&gt; 'dir1/dir2/new_dir/dir3/dir4/file.txt'
  </code></pre>
  
  <p>I looked through the os.path and pathlib packages, but it looks like they don't have a function that allows for inserting in the middle of a file path. I tried:</p>
  
  <pre><code>import sys,os
  from os.path import join
  
  path_ = file_path0.split(os.sep)
  path_.insert(2, 'new_dir')
  print(join(path_))
  </code></pre>
  
  <p>but this results in the error</p>
  
  <p>"expected str, bytes or os.PathLike object, not list"</p>
  
  <p>Does anyone know standard python functions that allow such inserting in the middle of a file path? Alternatively - how can I turn <code>path_</code> to something that can be processed by <code>os.path</code>. I am new to pathlib, so maybe I missed something out there</p>
  
  <hr>
  
  <p>Edit: Following the answers to the question I can suggest the following solutions:</p>
  
  <p>1.) As Zach Favakeh suggests and as written in <a href="https://stackoverflow.com/a/14826889/5838180">this answer</a> just correct my code above to <code>join(*path_)</code> by using the 'splat' operator <code>*</code> and everything is solved.</p>
  
  <p>2.) As suggested by buran you can use the <code>pathlib</code> package, in very short it results in:</p>
  
  <pre><code>from pathlib import PurePath
  
  path_list = list(PurePath(file_path0).parts)
  path_list.insert(2, 'new_dir')
  file_path1 = PurePath('').joinpath(*path_list)
  
  print(file_path1)
  &gt;&gt;&gt; 'dir1/dir2/new_dir/dir3/dir4/file.txt'
  </code></pre>