4

Below is a small test routine which takes a path to a file and moves the file up one directory. I am using the os and shutil modules, is there one module that could perform this task? Is there a more pythonic way of implementing this functionality?

The code below is running on windows, but the best cross-platform solution would be appreciated.

def up_one_directory(path):
    """Move file in path up one directory"""
    head, tail = os.path.split(path)
    try:
        shutil.move(path, os.path.join(os.path.split(head)[0], tail))
    except Exception as ex:
        # report
        pass
10SecTom
  • 2,484
  • 4
  • 22
  • 26

3 Answers3

14

This is the same as @thierry-lathuille's answer, but without requiring shutil:

p = Path(path).absolute()
parent_dir = p.parents[1]
p.rename(parent_dir / p.name)
Neuron
  • 5,141
  • 5
  • 38
  • 59
kepler
  • 1,712
  • 17
  • 18
  • 3
    Thought there were issues using rename, but I was incorrect - this worked a treat. – 10SecTom May 16 '18 at 12:12
  • And note that we need to make sure the new path directory exists. In the case of the parent directory, this is always true. – 0dminnimda Jul 26 '21 at 23:26
  • 1
    `Path.rename` does not always work, for example when moving files from one drive to another. So this is NOT "the same" as the linked answer. – Neuron Feb 19 '23 at 16:17
6

Since Python 3.4, you can use the pathlib module:

import shutil
from pathlib import Path

    
def up_one_dir(path):
    try:
        # from Python 3.6
        parent_dir = Path(path).parents[1]
        # for Python 3.4/3.5, use str to convert the path to string
        # parent_dir = str(Path(path).parents[1])
        shutil.move(path, parent_dir)
    except IndexError:
        # no upper directory
        pass
    
Neuron
  • 5,141
  • 5
  • 38
  • 59
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

Use this to move up one directory:

file_path = os.getcwd()
os.chdir("..")
folder_path = os.getcwd()
shutil.copy(file_path, folder_path)
Neuron
  • 5,141
  • 5
  • 38
  • 59
KnakworstKoning
  • 361
  • 3
  • 6
  • 18
  • I mean to take a physical file and move it from its current directory to the one the next level up. – 10SecTom Mar 27 '18 at 11:36