[英]How to safely move a file to another directory in Python
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.
Windows 和 Unix 都很好。 If not, Unix at least.
如果没有,至少 Unix。
You could use pathlib
's purepath.suffix
to determine if a path points to a file or a directory, like so:您可以使用
pathlib
的purepath.suffix
来确定路径是指向文件还是目录,如下所示:
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
You can define a custom function to ensure that source
is a file (with os.path.isfile
function):您可以定义自定义 function 以确保
source
是一个文件(使用os.path.isfile
函数):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.