Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: move a file up one directory

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
like image 495
10SecTom Avatar asked Dec 03 '22 20:12

10SecTom


2 Answers

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)
like image 143
kepler Avatar answered Feb 14 '23 23:02

kepler


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
like image 20
Thierry Lathuille Avatar answered Feb 15 '23 00:02

Thierry Lathuille