title: What is the most elegant way to go into a subdirectory, run a command, and come back out?
body: <p>I have the following directory structure. </p>
  
  <pre><code> data
  │   ├── 2019-12-11
  │   └── 2019-12-12
  │       ├── ADAZ19.json
  │       ├── BCHZ19.json
  </code></pre>
  
  <p>I want to go in, run a tar command from os.system, and then go back out to where I started.</p>
  
  <p>I tried something like below:</p>
  
  <pre><code># Full filepath from root.
  import os
  path_to_file = 'data/2019-12-12/' # This is generated dynamically.
  file = 'ADAZ19.json' # This is generated dynamically.
  cur_dir = os.getcwd()
  os.system(f'tar -czf {cur_dir}{path_to_file}{file}.tar.gz {cur_dir}{path_to_file}{file}')
  </code></pre>
  
  <p>Which didnt work. So now I want to go into <code>path_to_file</code>, run tar there directly on the file, then go back up to where I started. Note, <code>path_to_file</code> is set by the user and can't be hardcoded.</p>
  
  <p>I want to go into the subdirectory so that the directory structure doesn't get tarred with the file. What is the most elegant way to do so?</p>