Home > Net >  How to safely move a file to another directory in Python
How to safely move a file to another directory in Python

Time:01-28

The below works as expected:

import shutil
source = "c:\\mydir\myfile.txt"
dest_dir = "c:\\newdir"
shutil.move(source,dest_dir)

However, this also succeeds. I would want this to fail.

import shutil
source = "c:\\mydir"
dest_dir = "c:\\newdir"
shutil.move(source,dest_dir)

Any way to ensure that only a file is moved. Both Windows and Unix would be great. If not, Unix at least.

CodePudding user response:

You could use pathlib's purepath.suffix to determine if a path points to a file or a directory, like so:

import pathlib

def points_to_file(path) -> bool:
    if pathlib.PurePath(path).suffix:
        return True
    else:
        return False
    
pathtodir = r'C:\Users\username'
pathtofile = r'C:\Users\username\filename.extension'

print (f'Does "{pathtodir}" point to a file? {points_to_file(pathtodir)}')
# Result -> Does "C:\Users\username" point to a file? False
print (f'Does "{pathtofile}" point to a file? {points_to_file(pathtofile)}')
# Result -> Does "C:\Users\username\filename.extension" point to a file? True

CodePudding user response:

You can define a custom function to ensure that source is a file (with os.path.isfile function):

from os import path

def move_file(src, dst):
    if not path.isfile(src):
        raise IsADirectoryError('Source is not a file')
    shutil.move(src, dst)
  • Related