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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With